diff --git a/java/com.sap.sailing.gwt.ui/SailingGWT Remote Profiling.launch b/java/com.sap.sailing.gwt.ui/SailingGWT Remote Profiling.launch index d851188e1cd..0c012601c94 100755 --- a/java/com.sap.sailing.gwt.ui/SailingGWT Remote Profiling.launch +++ b/java/com.sap.sailing.gwt.ui/SailingGWT Remote Profiling.launch @@ -1,54 +1,54 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/de.csenk.gwt.ws/.classpath b/java/de.csenk.gwt.ws/.classpath deleted file mode 100755 index 8533223089a..00000000000 --- a/java/de.csenk.gwt.ws/.classpath +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/java/de.csenk.gwt.ws/.project b/java/de.csenk.gwt.ws/.project deleted file mode 100755 index b1a9930e81a..00000000000 --- a/java/de.csenk.gwt.ws/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - de.csenk.gwt.ws - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/java/de.csenk.gwt.ws/.settings/org.eclipse.jdt.core.prefs b/java/de.csenk.gwt.ws/.settings/org.eclipse.jdt.core.prefs deleted file mode 100755 index c537b63063c..00000000000 --- a/java/de.csenk.gwt.ws/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,7 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.6 diff --git a/java/de.csenk.gwt.ws/.settings/org.eclipse.pde.core.prefs b/java/de.csenk.gwt.ws/.settings/org.eclipse.pde.core.prefs deleted file mode 100755 index f29e940a005..00000000000 --- a/java/de.csenk.gwt.ws/.settings/org.eclipse.pde.core.prefs +++ /dev/null @@ -1,3 +0,0 @@ -eclipse.preferences.version=1 -pluginProject.extensions=false -resolve.requirebundle=false diff --git a/java/de.csenk.gwt.ws/META-INF/MANIFEST.MF b/java/de.csenk.gwt.ws/META-INF/MANIFEST.MF deleted file mode 100755 index 6ea17fc833c..00000000000 --- a/java/de.csenk.gwt.ws/META-INF/MANIFEST.MF +++ /dev/null @@ -1,26 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: GWT Web Sockets -Bundle-SymbolicName: de.csenk.gwt.ws -Bundle-Version: 1.0.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Require-Bundle: org.eclipse.jetty.websocket.api;bundle-version="9.0.0", - com.google.gwt.osgi;bundle-version="2.6.0" -Export-Package: de.csenk.gwt.ws.client, - de.csenk.gwt.ws.client.filter, - de.csenk.gwt.ws.client.filter.serialization, - de.csenk.gwt.ws.client.handler, - de.csenk.gwt.ws.client.js, - de.csenk.gwt.ws.rebind.filter.serialization, - de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc, - de.csenk.gwt.ws.server.filter, - de.csenk.gwt.ws.server.filter.serialization, - de.csenk.gwt.ws.server.handler, - de.csenk.gwt.ws.server.jetty, - de.csenk.gwt.ws.shared, - de.csenk.gwt.ws.shared.filter, - de.csenk.gwt.ws.shared.filter.requestresponse, - de.csenk.gwt.ws.shared.filter.serialization, - de.csenk.gwt.ws.shared.handler -Import-Package: javax.servlet;version="2.6.0", - javax.servlet.http;version="2.6.0" diff --git a/java/de.csenk.gwt.ws/build.properties b/java/de.csenk.gwt.ws/build.properties deleted file mode 100755 index 34d2e4d2dad..00000000000 --- a/java/de.csenk.gwt.ws/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - . diff --git a/java/de.csenk.gwt.ws/pom.xml b/java/de.csenk.gwt.ws/pom.xml deleted file mode 100755 index 8775b6d3cc7..00000000000 --- a/java/de.csenk.gwt.ws/pom.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - 4.0.0 - - root - com.sap.sailing - 1.0.0-SNAPSHOT - - de.csenk.gwt.ws - eclipse-plugin - - - - - org.eclipse.tycho - tycho-source-plugin - ${tycho-version} - - - plugin-source - generate-sources - - plugin-source - - - - - - - diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/WebSocket.gwt.xml b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/WebSocket.gwt.xml deleted file mode 100755 index cd63b143820..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/WebSocket.gwt.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/WebSocket.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/WebSocket.java deleted file mode 100755 index d58de2dddad..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/WebSocket.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.client; - -import de.csenk.gwt.ws.client.js.JavaScriptWebSocket; - -/** - * @author senk.christian@googlemail.com - * @date 02.09.2010 - * @time 14:45:42 - * - */ -public interface WebSocket { - - /** - * Sends a message. - * - * @param message - */ - public void send(String message); - - /** - * Closes this {@link JavaScriptWebSocket}. - */ - public void close(); - - /** - * @return the bufferedAmount property of the underlying JavaScript WebSocket. - */ - public int getBufferedAmount(); - - /** - * @return the readyState property of the underlying JavaScript WebSocket. - */ - public int getReadyState(); - - /** - * @return the url property of the underlying JavaScript WebSocket. - */ - public String getURL(); - -} \ No newline at end of file diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/WebSocketCallback.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/WebSocketCallback.java deleted file mode 100755 index 2c049cb994e..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/WebSocketCallback.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.client; - -import de.csenk.gwt.ws.client.js.JavaScriptWebSocket; - -/** - * @author senk.christian@googlemail.com - * @date 25.08.2010 - * @time 12:08:28 - * - * Interface definition to create a call-back for a {@link JavaScriptWebSocket}. - */ -public interface WebSocketCallback { - - /** - * Called if the {@link JavaScriptWebSocket} has opened. - * - * @param webSocket - */ - void onOpen(WebSocket webSocket); - - /** - * Called if the {@link JavaScriptWebSocket} was closed. - * - * @param webSocket - */ - void onClose(WebSocket webSocket); - - /** - * Called if a message arrived in the {@link JavaScriptWebSocket}. - * - * @param webSocket - * @param message the delivered message. - */ - void onMessage(WebSocket webSocket, String message); - - /** - * Called if an error occurred during the usage of the {@link JavaScriptWebSocket} - * - * @param webSocket - */ - void onError(WebSocket webSocket); - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/WebSocketConnection.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/WebSocketConnection.java deleted file mode 100755 index c9a3edbcf01..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/WebSocketConnection.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.client; - -import de.csenk.gwt.ws.shared.Connection; -import de.csenk.gwt.ws.shared.FilterChain; -import de.csenk.gwt.ws.shared.Handler; -import de.csenk.gwt.ws.shared.Sender; -import de.csenk.gwt.ws.shared.filter.DefaultFilterChain; - -/** - * @author senk.christian@googlemail.com - * @date 26.08.2010 - * @time 13:44:45 - * - */ -public class WebSocketConnection implements Connection { - - private final Handler handler; - private final WebSocketFactory socketFactory; - - private final WebSocket webSocket; - private final Sender webSocketSender; - - private final FilterChain filterChain; - - /** - * @param url - * @param handler - */ - public WebSocketConnection(final String url, final Handler handler, final WebSocketFactory socketFactory) { - this.handler = handler; - this.socketFactory = socketFactory; - - this.webSocket = createWebSocket(url); - - this.webSocketSender = new WebSocketSender(webSocket); - this.filterChain = new DefaultFilterChain(this); - } - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.shared.Connection#close() - */ - @Override - public void close() { - webSocket.close(); - } - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.shared.Connection#getFilterChain() - */ - @Override - public FilterChain getFilterChain() { - return filterChain; - } - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.shared.Connection#getHandler() - */ - @Override - public Handler getHandler() { - return handler; - } - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.shared.Connection#getSender() - */ - @Override - public Sender getSender() { - return webSocketSender; - } - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.shared.Connection#send(java.lang.Object) - */ - @Override - public void send(Object message) { - filterChain.fireSend(message); - } - - /** - * @param url - * @return - */ - private WebSocket createWebSocket(String url) { - return socketFactory.createWebSocket(url, new WebSocketCallback() { - - @Override - public void onOpen(WebSocket webSocket) { - filterChain.fireConnectionOpened(); - } - - @Override - public void onMessage(WebSocket webSocket, String message) { - filterChain.fireMessageReceived(message); - } - - @Override - public void onError(WebSocket webSocket) { - filterChain.fireExceptionCaught(new IllegalStateException("JavaScript implementation of WebSocket thrown an unknown exception.")); - } - - @Override - public void onClose(WebSocket webSocket) { - filterChain.fireConnectionClosed(); - } - - }); - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/WebSocketFactory.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/WebSocketFactory.java deleted file mode 100755 index 6ea787b460b..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/WebSocketFactory.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.client; - -/** - * @author senk.christian@googlemail.com - * @date 09.10.2010 - * @time 11:19:27 - * - * Factory interface to create web sockets - */ -public interface WebSocketFactory { - - /** - * Creates a {@link WebSocket} implementation. - * - * @param url - * @param callback - * @return - */ - WebSocket createWebSocket(String url, WebSocketCallback callback); - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/WebSocketSender.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/WebSocketSender.java deleted file mode 100755 index 3e746090313..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/WebSocketSender.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.client; - -import java.io.IOException; - -import de.csenk.gwt.ws.shared.Sender; - -/** - * @author senk.christian@googlemail.com - * @date 31.08.2010 - * @time 15:38:55 - * - */ -public class WebSocketSender implements Sender { - - private final WebSocket webSocket; - - public WebSocketSender(WebSocket webSocket) { - this.webSocket = webSocket; - } - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.shared.Sender#send(java.lang.String) - */ - @Override - public void send(String message) throws IOException { - webSocket.send(message); - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/filter/ClientLoggingFilter.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/filter/ClientLoggingFilter.java deleted file mode 100755 index 7a591f45b47..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/filter/ClientLoggingFilter.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.client.filter; - -import java.util.logging.Logger; - -import de.csenk.gwt.ws.shared.Connection; -import de.csenk.gwt.ws.shared.filter.DefaultFilter; - -/** - * @author senk.christian@googlemail.com - * @date 01.09.2010 - * @time 14:33:31 - * - */ -public class ClientLoggingFilter extends DefaultFilter { - private static final Logger logger = Logger.getLogger(ClientLoggingFilter.class.getName()); - - /* - * (non-Javadoc) - * - * @see de.csenk.gwt.ws.shared.filter.FilterImpl#onMessageReceived(de.csenk.gwt.ws.shared.Filter.NextFilter, - * de.csenk.gwt.ws.shared.Connection, java.lang.Object) - */ - @Override - public void onMessageReceived(NextFilter nextFilter, Connection connection, Object message) throws Throwable { - logger.info(message.toString()); - super.onMessageReceived(nextFilter, connection, message); - } - - /* - * (non-Javadoc) - * - * @see de.csenk.gwt.ws.shared.filter.FilterImpl#onSend(de.csenk.gwt.ws.shared.Filter.NextFilter, - * de.csenk.gwt.ws.shared.Connection, java.lang.Object) - */ - @Override - public void onSend(NextFilter nextFilter, Connection connection, Object message) throws Throwable { - logger.info(message.toString()); - super.onSend(nextFilter, connection, message); - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/filter/serialization/ClientGWTSerializationFilter.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/filter/serialization/ClientGWTSerializationFilter.java deleted file mode 100755 index 50ee4e7a794..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/filter/serialization/ClientGWTSerializationFilter.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.client.filter.serialization; - -import de.csenk.gwt.ws.shared.Connection; -import de.csenk.gwt.ws.shared.filter.DefaultFilter; -import de.csenk.gwt.ws.shared.filter.serialization.GWTSerializer; - -/** - * @author senk.christian@googlemail.com - * @date 01.09.2010 - * @time 14:25:40 - * - */ -public class ClientGWTSerializationFilter extends DefaultFilter { - - private final GWTSerializer serializer; - - public ClientGWTSerializationFilter(GWTSerializer gwtSerializer) { - this.serializer = gwtSerializer; - } - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.shared.filter.FilterImpl#onMessageReceived(de.csenk.gwt.ws.shared.Filter.NextFilter, de.csenk.gwt.ws.shared.Connection, java.lang.Object) - */ - @Override - public void onMessageReceived(NextFilter nextFilter, Connection connection, - Object message) throws Throwable { - assert message instanceof String; - - Object deserializedMessage = serializer.deserialize((String) message); - nextFilter.onMessageReceived(connection, deserializedMessage); - } - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.shared.filter.FilterImpl#onSend(de.csenk.gwt.ws.shared.Filter.NextFilter, de.csenk.gwt.ws.shared.Connection, java.lang.Object) - */ - @Override - public void onSend(NextFilter nextFilter, Connection connection, - Object message) throws Throwable { - Object serializedMessage = serializer.serialize(message); - nextFilter.onSend(connection, serializedMessage); - } - - /** - * @return the serializer - */ - public GWTSerializer getSerializer() { - return serializer; - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/filter/serialization/ClientGWTSerializer.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/filter/serialization/ClientGWTSerializer.java deleted file mode 100755 index 5288bd8e964..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/filter/serialization/ClientGWTSerializer.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.client.filter.serialization; - -import java.util.HashMap; -import java.util.Map; - -import com.google.gwt.user.client.rpc.SerializationException; -import com.google.gwt.user.client.rpc.impl.ClientSerializationStreamReader; -import com.google.gwt.user.client.rpc.impl.ClientSerializationStreamWriter; -import com.google.gwt.user.client.rpc.impl.Serializer; - -import de.csenk.gwt.ws.shared.filter.serialization.GWTSerializer; - -/** - * @author senk.christian@googlemail.com - * @date 28.08.2010 - * @time 19:05:44 - * - */ -public abstract class ClientGWTSerializer implements GWTSerializer { - - private final String moduleBaseURL; - private final Serializer serializer; - private final String serializationPolicyName; - - protected final Map typeStringMap = new HashMap(); - - protected ClientGWTSerializer(String moduleBaseURL, - String serializationPolicyName, Serializer serializer) { - this.moduleBaseURL = moduleBaseURL; - this.serializer = serializer; - this.serializationPolicyName = serializationPolicyName; - } - - /* - * (non-Javadoc) - * - * @see - * de.csenk.gwt.ws.shared.filter.serialization.GWTSerializer#deserialize( - * java.lang.String) - */ - @Override - public Object deserialize(String serializedContent) - throws SerializationException { - ClientSerializationStreamReader streamReader = new ClientSerializationStreamReader(serializer); - streamReader.prepareToRead(serializedContent); - - String className = streamReader.readString(); - if (className.equals("java.lang.String")) { - return streamReader.readString(); - } else { - return streamReader.readObject(); - } - } - - /* - * (non-Javadoc) - * - * @see - * de.csenk.gwt.ws.shared.filter.serialization.GWTSerializer#serialize(java - * .lang.Object) - */ - @Override - public String serialize(Object obj) throws SerializationException { - ClientSerializationStreamWriter streamWriter = new ClientSerializationStreamWriter( - serializer, moduleBaseURL, serializationPolicyName); - streamWriter.prepareToWrite(); - - String typeString = typeStringMap.get(obj.getClass().getName()); - if (typeString == null || typeString.length() <= 0) - throw new SerializationException("Serializer tried to serialize an unmapped class '" + obj.getClass().getName() + "'"); - - streamWriter.writeString(typeString); - - if (obj instanceof String) { - streamWriter.writeString((String) obj); - } else { - streamWriter.writeObject(obj); - } - - return streamWriter.toString(); - } -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/handler/ClientMessageDispatchingHandler.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/handler/ClientMessageDispatchingHandler.java deleted file mode 100755 index ef1ae0815ec..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/handler/ClientMessageDispatchingHandler.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.client.handler; - -import java.util.Map; -import java.util.Set; - -import de.csenk.gwt.ws.shared.handler.DefaultMessageDispatchingHandler; - -/** - * @author senk.christian@googlemail.com - * @date 09.09.2010 - * @time 21:40:02 - * - */ -public class ClientMessageDispatchingHandler extends - DefaultMessageDispatchingHandler { - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.shared.handler.DefaultMessageDispatchingHandler#findHandler(java.util.Map, java.lang.Class, java.util.Set) - */ - @SuppressWarnings("rawtypes") - @Override - protected Object findHandler(Map handlers, Class type, Set triedTypes) { - if (handlers == null || type == null) - return null; - - if (handlers.containsKey(type)) - return handlers.get(type); - - Class superClass = type.getSuperclass(); - return findHandler(handlers, superClass, null); - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/js/JavaScriptWebSocket.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/js/JavaScriptWebSocket.java deleted file mode 100755 index dea832711e9..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/js/JavaScriptWebSocket.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.client.js; - -import com.google.gwt.core.client.JavaScriptObject; - -import de.csenk.gwt.ws.client.WebSocket; -import de.csenk.gwt.ws.client.WebSocketCallback; - -/** - * @author senk.christian@googlemail.com - * @date 25.08.2010 - * @time 12:04:46 - * - * Represents the GWT version of the JavaScripts new WebSocket component. - */ -public class JavaScriptWebSocket implements WebSocket { - - /** - * @return True if the WebSocket component is supported by the current browser - */ - public static native boolean IsSupported() /*-{ - if ($wnd.WebSocket) { - return true; - } else { - return false; - } - }-*/; - - private final JavaScriptObject jsWebSocket; - private final WebSocketCallback socketCallback; - - /** - * Creates a new {@link JavaScriptWebSocket} that connects immediately to the end-point URL. - * - * @param url - * @param socketCallback - */ - public JavaScriptWebSocket(final String url, final WebSocketCallback socketCallback) { - assert url != null; - assert socketCallback != null; - assert IsSupported(); - - this.socketCallback = socketCallback; - this.jsWebSocket = createJSWebSocket(url, this); - } - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.client.js.WebSocket#send(java.lang.String) - */ - @Override - public native void send(String message) /*-{ - if (message == null) - return; - - this.@de.csenk.gwt.ws.client.js.JavaScriptWebSocket::jsWebSocket.send(message); - }-*/; - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.client.js.WebSocket#close() - */ - @Override - public native void close() /*-{ - this.@de.csenk.gwt.ws.client.js.JavaScriptWebSocket::jsWebSocket.close(); - }-*/; - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.client.js.WebSocket#getBufferedAmount() - */ - @Override - public native int getBufferedAmount() /*-{ - return this.@de.csenk.gwt.ws.client.js.JavaScriptWebSocket::jsWebSocket.bufferedAmount; - }-*/; - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.client.js.WebSocket#getReadyState() - */ - @Override - public native int getReadyState() /*-{ - return this.@de.csenk.gwt.ws.client.js.JavaScriptWebSocket::jsWebSocket.readyState; - }-*/; - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.client.js.WebSocket#getURL() - */ - @Override - public native String getURL() /*-{ - return this.@de.csenk.gwt.ws.client.js.JavaScriptWebSocket::jsWebSocket.url; - }-*/; - - /** - * Creates the JavaScript WebSocket component and set's all callback handlers. - * - * @param url - */ - private native JavaScriptObject createJSWebSocket(final String url, final WebSocket webSocket) /*-{ - var jsWebSocket = new WebSocket(url); - - jsWebSocket.onopen = function() { - webSocket.@de.csenk.gwt.ws.client.js.JavaScriptWebSocket::onOpen()(); - } - - jsWebSocket.onclose = function() { - webSocket.@de.csenk.gwt.ws.client.js.JavaScriptWebSocket::onClose()(); - } - - jsWebSocket.onerror = function() { - webSocket.@de.csenk.gwt.ws.client.js.JavaScriptWebSocket::onError()(); - } - - jsWebSocket.onmessage = function(socketResponse) { - if (socketResponse.data) { - webSocket.@de.csenk.gwt.ws.client.js.JavaScriptWebSocket::onMessage(Ljava/lang/String;)(socketResponse.data); - } - } - - return jsWebSocket; - }-*/; - - /** - * - */ - private void onOpen() { - socketCallback.onOpen(this); - } - - /** - * @param message - */ - private void onMessage(String message) { - socketCallback.onMessage(this, message); - } - - /** - * - */ - private void onError() { - socketCallback.onError(this); - } - - /** - * - */ - private void onClose() { - socketCallback.onClose(this); - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/js/JavaScriptWebSocketFactory.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/js/JavaScriptWebSocketFactory.java deleted file mode 100755 index 1f414f1f1d5..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/client/js/JavaScriptWebSocketFactory.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.client.js; - -import de.csenk.gwt.ws.client.WebSocket; -import de.csenk.gwt.ws.client.WebSocketCallback; -import de.csenk.gwt.ws.client.WebSocketFactory; - -/** - * @author senk.christian@googlemail.com - * @date 09.10.2010 - * @time 11:21:56 - * - */ -public class JavaScriptWebSocketFactory implements WebSocketFactory { - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.client.WebSocketFactory#createWebSocket(java.lang.String, de.csenk.gwt.ws.client.WebSocketCallback) - */ - @Override - public WebSocket createWebSocket(String url, WebSocketCallback callback) { - return new JavaScriptWebSocket(url, callback); - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/GWTSerializerGenerator.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/GWTSerializerGenerator.java deleted file mode 100755 index 5eb46248a17..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/GWTSerializerGenerator.java +++ /dev/null @@ -1,579 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.rebind.filter.serialization; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.UnsupportedEncodingException; -import java.util.Arrays; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import com.google.gwt.core.client.GWT; -import com.google.gwt.core.ext.Generator; -import com.google.gwt.core.ext.GeneratorContext; -import com.google.gwt.core.ext.PropertyOracle; -import com.google.gwt.core.ext.TreeLogger; -import com.google.gwt.core.ext.UnableToCompleteException; -import com.google.gwt.core.ext.linker.EmittedArtifact.Visibility; -import com.google.gwt.core.ext.linker.GeneratedResource; -import com.google.gwt.core.ext.typeinfo.JClassType; -import com.google.gwt.core.ext.typeinfo.JField; -import com.google.gwt.core.ext.typeinfo.JPackage; -import com.google.gwt.core.ext.typeinfo.JType; -import com.google.gwt.core.ext.typeinfo.NotFoundException; -import com.google.gwt.core.ext.typeinfo.TypeOracle; -import com.google.gwt.dev.util.Util; -import com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException; -import com.google.gwt.user.linker.rpc.RpcPolicyFileArtifact; -import com.google.gwt.user.rebind.ClassSourceFileComposerFactory; -import com.google.gwt.user.rebind.SourceWriter; -import com.google.gwt.user.server.rpc.SerializationPolicyLoader; -import com.google.gwt.user.server.rpc.impl.TypeNameObfuscator; - -import de.csenk.gwt.ws.client.filter.serialization.ClientGWTSerializer; -import de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc.BlacklistTypeFilter; -import de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc.SerializableTypeOracle; -import de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc.SerializableTypeOracleBuilder; -import de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc.SerializationUtils; -import de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc.Shared; -import de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc.TypeFilter; -import de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc.TypeSerializerCreator; -import de.csenk.gwt.ws.shared.filter.serialization.Serializable; - -/** - * @author senk.christian@googlemail.com - * @date 27.08.2010 - * @time 14:25:20 - * - */ -public class GWTSerializerGenerator extends Generator { - - private static final String IMPLEMENTATION_SUFFIX = "_Impl"; - - /** - * Compares {@link JType}s according to their qualified source names. - */ - static final Comparator JTYPE_COMPARATOR = new Comparator() { - public int compare(JType t1, JType t2) { - return t1.getQualifiedSourceName().compareTo( - t2.getQualifiedSourceName()); - } - }; - - /* - * (non-Javadoc) - * - * @see - * com.google.gwt.core.ext.Generator#generate(com.google.gwt.core.ext.TreeLogger - * , com.google.gwt.core.ext.GeneratorContext, java.lang.String) - */ - @Override - public String generate(TreeLogger logger, GeneratorContext context, - String typeName) throws UnableToCompleteException { - TypeOracle typeOracle = context.getTypeOracle(); - assert (typeOracle != null); - - JClassType serializerInterface = typeOracle.findType(typeName); - if (serializerInterface == null) { - logger.log(TreeLogger.ERROR, "Unable to find metadata for type '" - + typeName + "'", null); - throw new UnableToCompleteException(); - } - - if (serializerInterface.isInterface() == null) { - logger.log(TreeLogger.ERROR, serializerInterface - .getQualifiedSourceName() - + " is not an interface", null); - throw new UnableToCompleteException(); - } - - TreeLogger serializerLogger = logger.branch(TreeLogger.DEBUG, - "Generating implementation for serializer '" - + serializerInterface.getQualifiedSourceName() + "'", - null); - - return createSerializer(serializerLogger, context, serializerInterface); - } - - /** - * @param serializerLogger - * @param context - * @param serializerInterface - * @return - */ - private String createSerializer(TreeLogger serializerLogger, - GeneratorContext context, JClassType serializerInterface) - throws UnableToCompleteException { - TypeOracle typeOracle = context.getTypeOracle(); - SourceWriter sourceWriter = getSourceWriter(serializerLogger, context, - serializerInterface); - if (sourceWriter == null) - return getImplementationQualifiedName(serializerInterface); - - // TODO gwtws: validate serializerInterface - - final PropertyOracle propertyOracle = context.getPropertyOracle(); - - // Load the blacklist/whitelist - TypeFilter blacklistTypeFilter = new BlacklistTypeFilter( - serializerLogger, propertyOracle); - - // Determine the set of serializable types - SerializableTypeOracleBuilder typesSentFromBrowserBuilder = new SerializableTypeOracleBuilder( - serializerLogger, propertyOracle, typeOracle); - typesSentFromBrowserBuilder.setTypeFilter(blacklistTypeFilter); - SerializableTypeOracleBuilder typesSentToBrowserBuilder = new SerializableTypeOracleBuilder( - serializerLogger, propertyOracle, typeOracle); - typesSentToBrowserBuilder.setTypeFilter(blacklistTypeFilter); - - addRoots(serializerLogger, typeOracle, typesSentFromBrowserBuilder, - typesSentToBrowserBuilder, serializerInterface); - - // TODO gwtws: Type name ellision? - - // Create a resource file to receive all of the serialization - // information - // computed by STOB and mark it as private so it does not end up in the - // output. - OutputStream pathInfo = context.tryCreateResource(serializerLogger, - serializerInterface.getQualifiedSourceName() + ".rpc.log"); - PrintWriter writer = null; - SerializableTypeOracle typesSentFromBrowser; - SerializableTypeOracle typesSentToBrowser; - try { - writer = new PrintWriter(pathInfo); - - typesSentFromBrowserBuilder.setLogOutputStream(pathInfo); - typesSentToBrowserBuilder.setLogOutputStream(pathInfo); - - writer.write("====================================\n"); - writer.write("Types potentially sent from browser:\n"); - writer.write("====================================\n\n"); - writer.flush(); - typesSentFromBrowser = typesSentFromBrowserBuilder - .build(serializerLogger); - - writer.write("===================================\n"); - writer.write("Types potentially sent from server:\n"); - writer.write("===================================\n\n"); - writer.flush(); - typesSentToBrowser = typesSentToBrowserBuilder - .build(serializerLogger); - - if (pathInfo != null) { - context.commitResource(serializerLogger, pathInfo).setVisibility(Visibility.Private); - } - } finally { - if (writer != null) { - writer.close(); - } - } - - Map typeStrings = generateTypeHandlers(serializerLogger, - context, typesSentFromBrowser, typesSentToBrowser, - serializerInterface); - - String serializationPolicyStrongName = writeSerializationPolicyFile( - serializerLogger, context, typesSentFromBrowser, - typesSentToBrowser, typeStrings, serializerInterface); - - String serializerInterfaceName = serializerInterface.getQualifiedBinaryName(); - generateFields(sourceWriter, typesSentFromBrowser, - serializationPolicyStrongName, serializerInterfaceName, - serializerInterface); - - generateContructor(sourceWriter, serializerInterface, typeStrings); - - sourceWriter.commit(serializerLogger); - return getImplementationQualifiedName(serializerInterface); - } - - /** - * Generate any fields required by the proxy. - */ - private void generateFields(SourceWriter srcWriter, - SerializableTypeOracle serializableTypeOracle, - String serializationPolicyStrongName, - String remoteServiceInterfaceName, JClassType serializerInterface) { - // Initialize a field with binary name of the remote service interface - srcWriter - .println("private static final String INTERFACE_NAME = " - + "\"" + remoteServiceInterfaceName + "\";"); - srcWriter - .println("private static final String SERIALIZATION_POLICY =\"" - + serializationPolicyStrongName + "\";"); - String typeSerializerName = SerializationUtils - .getTypeSerializerQualifiedName(serializerInterface); - srcWriter.println("private static final " + typeSerializerName - + " SERIALIZER = new " + typeSerializerName + "();"); - srcWriter.println(); - } - - /** - * @param serializerLogger - * @param context - * @param typesSentFromBrowser - * @param typesSentToBrowser - * @param typeStrings - * @return - */ - private String writeSerializationPolicyFile(TreeLogger logger, - GeneratorContext ctx, SerializableTypeOracle serializationSto, - SerializableTypeOracle deserializationSto, - Map typeStrings, JClassType serializerInterface) - throws UnableToCompleteException { - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - OutputStreamWriter osw = new OutputStreamWriter( - baos, - SerializationPolicyLoader.SERIALIZATION_POLICY_FILE_ENCODING); - TypeOracle oracle = ctx.getTypeOracle(); - PrintWriter pw = new PrintWriter(osw); - - JType[] serializableTypes = unionOfTypeArrays(serializationSto - .getSerializableTypes(), deserializationSto - .getSerializableTypes(), - new JType[] { serializerInterface }); - - for (int i = 0; i < serializableTypes.length; ++i) { - JType type = serializableTypes[i]; - String binaryTypeName = type.getQualifiedBinaryName(); - pw.print(binaryTypeName); - pw.print(", " - + Boolean.toString(deserializationSto - .isSerializable(type))); - pw.print(", " - + Boolean.toString(deserializationSto - .maybeInstantiated(type))); - pw.print(", " - + Boolean.toString(serializationSto - .isSerializable(type))); - pw.print(", " - + Boolean.toString(serializationSto - .maybeInstantiated(type))); - pw.print(", " + typeStrings.get(type)); - - /* - * Include the serialization signature to bump the RPC file name - * if obfuscated identifiers are used. - */ - pw.print(", " - + SerializationUtils.getSerializationSignature(oracle, - type)); - pw.print('\n'); - - /* - * Emit client-side field information for classes that may be - * enhanced on the server. Each line consists of a - * comma-separated list containing the keyword '@ClientFields', - * the class name, and a list of all potentially serializable - * client-visible fields. - */ - if ((type instanceof JClassType) - && ((JClassType) type).isEnhanced()) { - JField[] fields = ((JClassType) type).getFields(); - JField[] rpcFields = new JField[fields.length]; - int numRpcFields = 0; - for (JField f : fields) { - if (f.isTransient() || f.isStatic() || f.isFinal()) { - continue; - } - rpcFields[numRpcFields++] = f; - } - - pw.print(SerializationPolicyLoader.CLIENT_FIELDS_KEYWORD); - pw.print(','); - pw.print(binaryTypeName); - for (int idx = 0; idx < numRpcFields; idx++) { - pw.print(','); - pw.print(rpcFields[idx].getName()); - } - pw.print('\n'); - } - } - - // Closes the wrapped streams. - pw.close(); - - byte[] serializationPolicyFileContents = baos.toByteArray(); - String serializationPolicyName = Util - .computeStrongName(serializationPolicyFileContents); - - String serializationPolicyFileName = SerializationPolicyLoader - .getSerializationPolicyFileName(serializationPolicyName); - OutputStream os = ctx.tryCreateResource(logger, - serializationPolicyFileName); - if (os != null) { - os.write(serializationPolicyFileContents); - GeneratedResource resource = ctx.commitResource(logger, os); - - /* - * Record which proxy class created the resource. A manifest - * will be emitted by the RpcPolicyManifestLinker. - */ - ctx - .commitArtifact(logger, new RpcPolicyFileArtifact( - serializerInterface.getQualifiedSourceName(), - resource)); - } else { - logger.log(TreeLogger.TRACE, - "SerializationPolicy file for RemoteService '" - + serializerInterface.getQualifiedSourceName() - + "' already exists; no need to rewrite it.", - null); - } - - return serializationPolicyName; - } catch (UnsupportedEncodingException e) { - logger - .log( - TreeLogger.ERROR, - SerializationPolicyLoader.SERIALIZATION_POLICY_FILE_ENCODING - + " is not supported", e); - throw new UnableToCompleteException(); - } catch (IOException e) { - logger.log(TreeLogger.ERROR, null, e); - throw new UnableToCompleteException(); - } - } - - /** - * Take the union of two type arrays, and then sort the results - * alphabetically. - */ - private static JType[] unionOfTypeArrays(JType[]... types) { - Set typesList = new HashSet(); - for (JType[] a : types) { - typesList.addAll(Arrays.asList(a)); - } - JType[] serializableTypes = typesList.toArray(new JType[0]); - Arrays.sort(serializableTypes, JTYPE_COMPARATOR); - return serializableTypes; - } - - /** - * Generate the proxy constructor and delegate to the superclass constructor - * using the default address for the - * {@link com.google.gwt.user.client.rpc.RemoteService RemoteService}. - */ - private void generateContructor(SourceWriter srcWriter, JClassType serializerInterface, Map typeStrings) { - srcWriter.println("public " + getImplementationSimpleName(serializerInterface) + "() {"); - srcWriter.indent(); - srcWriter.println("super(GWT.getModuleBaseURL(),"); - srcWriter.indent(); - srcWriter.println("SERIALIZATION_POLICY, "); - srcWriter.println("SERIALIZER);"); - srcWriter.outdent(); - - srcWriter.println(); - for (Entry typeEntry : typeStrings.entrySet()) { - srcWriter.print("typeStringMap.put(\""); - srcWriter.print(typeEntry.getKey().getQualifiedSourceName() + "\", \""); - srcWriter.print(typeEntry.getValue()); - srcWriter.println("\");"); - } - - srcWriter.outdent(); - srcWriter.println("}"); - } - - /** - * @param logger - * @param context - * @param typesSentFromBrowser - * @param typesSentToBrowser - * @param serializerInterface - * @return - * @throws UnableToCompleteException - */ - private Map generateTypeHandlers(TreeLogger logger, - GeneratorContext context, - SerializableTypeOracle typesSentFromBrowser, - SerializableTypeOracle typesSentToBrowser, - JClassType serializerInterface) throws UnableToCompleteException { - TypeSerializerCreator tsc = new TypeSerializerCreator(logger, - typesSentFromBrowser, typesSentToBrowser, context, - SerializationUtils - .getTypeSerializerQualifiedName(serializerInterface)); - tsc.realize(logger); - - Map typeStrings = new HashMap(tsc - .getTypeStrings()); - typeStrings.put(serializerInterface, - TypeNameObfuscator.SERVICE_INTERFACE_ID); - return typeStrings; - } - - /** - * @param serializerLogger - * @param typeOracle - * @param typesSentFromBrowserBuilder - * @param typesSentToBrowserBuilder - */ - private void addRoots(TreeLogger serializerLogger, TypeOracle typeOracle, - SerializableTypeOracleBuilder typesSentFromBrowserBuilder, - SerializableTypeOracleBuilder typesSentToBrowserBuilder, - JClassType serializerInterface) throws UnableToCompleteException { - try { - addRequiredRoots(serializerLogger, typeOracle, - typesSentFromBrowserBuilder); - addRequiredRoots(serializerLogger, typeOracle, - typesSentToBrowserBuilder); - - addSerializerRootTypes(serializerLogger, typeOracle, - typesSentFromBrowserBuilder, typesSentToBrowserBuilder, - serializerInterface); - } catch (NotFoundException e) { - serializerLogger.log(TreeLogger.ERROR, - "Unable to find type referenced from remote service", e); - throw new UnableToCompleteException(); - } - } - - /** - * @param serializerLogger - * @param typeOracle - * @param typesSentFromBrowserBuilder - * @param typesSentToBrowserBuilder - * @param serializerInterface - */ - private void addSerializerRootTypes(TreeLogger serializerLogger, - TypeOracle typeOracle, - SerializableTypeOracleBuilder typesSentFromBrowserBuilder, - SerializableTypeOracleBuilder typesSentToBrowserBuilder, - JClassType serializerInterface) { - serializerLogger = serializerLogger.branch(TreeLogger.DEBUG, - "Analyzing '" - + serializerInterface - .getParameterizedQualifiedSourceName() - + "' for serializable types", null); - - if (!serializerInterface.isAnnotationPresent(Serializable.class)) - return; - - Serializable serializableAnnotation = serializerInterface - .getAnnotation(Serializable.class); - for (Class clazz : serializableAnnotation.value()) { - JClassType classType = typeOracle - .findType(clazz.getCanonicalName()); - - typesSentFromBrowserBuilder - .addRootType(serializerLogger, classType); - typesSentToBrowserBuilder.addRootType(serializerLogger, classType); - } - } - - /** - * Add the implicit root types that are needed to make RPC work. These would - * be {@link String} and {@link IncompatibleRemoteServiceException}. - */ - private static void addRequiredRoots(TreeLogger logger, - TypeOracle typeOracle, SerializableTypeOracleBuilder stob) - throws NotFoundException { - logger = logger.branch(TreeLogger.DEBUG, "Analyzing implicit types"); - - // String is always instantiable. - addRootType(logger, typeOracle, stob, String.class.getName()); - addRootType(logger, typeOracle, stob, Boolean.class.getName()); - addRootType(logger, typeOracle, stob, Byte.class.getName()); - addRootType(logger, typeOracle, stob, Short.class.getName()); - addRootType(logger, typeOracle, stob, Integer.class.getName()); - addRootType(logger, typeOracle, stob, Long.class.getName()); - addRootType(logger, typeOracle, stob, Float.class.getName()); - addRootType(logger, typeOracle, stob, Double.class.getName()); - - // IncompatibleRemoteServiceException is always serializable - JClassType icseType = typeOracle - .getType(IncompatibleRemoteServiceException.class.getName()); - stob.addRootType(logger, icseType); - } - - /** - * @param logger - * @param typeOracle - * @param stob - * @throws NotFoundException - */ - private static void addRootType(TreeLogger logger, TypeOracle typeOracle, - SerializableTypeOracleBuilder stob, String typeName) throws NotFoundException { - JClassType type = typeOracle.getType(typeName); - stob.addRootType(logger, type); - } - - /** - * @param logger - * @param ctx - * @param serializerInterface - * @return - */ - private SourceWriter getSourceWriter(TreeLogger logger, - GeneratorContext ctx, JClassType serializerInterface) { - JPackage serializerIntfPkg = serializerInterface.getPackage(); - String packageName = serializerIntfPkg == null ? "" : serializerIntfPkg - .getName(); - - PrintWriter printWriter = ctx.tryCreate(logger, packageName, - getImplementationSimpleName(serializerInterface)); - if (printWriter == null) { - return null; - } - - ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory( - packageName, getImplementationSimpleName(serializerInterface)); - - String[] imports = new String[] { ClientGWTSerializer.class - .getCanonicalName(), - GWT.class.getCanonicalName()}; - for (String imp : imports) { - composerFactory.addImport(imp); - } - - composerFactory.setSuperclass(ClientGWTSerializer.class - .getSimpleName()); - composerFactory.addImplementedInterface(serializerInterface - .getErasedType().getQualifiedSourceName()); - - return composerFactory.createSourceWriter(ctx, printWriter); - } - - /** - * @param serializerInterface - * @return - */ - private String getImplementationSimpleName(JClassType serializerInterface) { - String[] name = Shared.synthesizeTopLevelClassName(serializerInterface, - IMPLEMENTATION_SUFFIX); - return name[1]; - } - - /** - * @param serializerInterface - * @return - */ - private String getImplementationQualifiedName(JClassType serializerInterface) { - String[] name = Shared.synthesizeTopLevelClassName(serializerInterface, - IMPLEMENTATION_SUFFIX); - return name[0].length() == 0 ? name[1] : name[0] + "." + name[1]; - } -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/BlacklistTypeFilter.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/BlacklistTypeFilter.java deleted file mode 100755 index 718fc74c854..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/BlacklistTypeFilter.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright 2009 Google Inc. - * - * 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 de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc; - -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Pattern; -import java.util.regex.PatternSyntaxException; - -import com.google.gwt.core.ext.BadPropertyValueException; -import com.google.gwt.core.ext.ConfigurationProperty; -import com.google.gwt.core.ext.PropertyOracle; -import com.google.gwt.core.ext.TreeLogger; -import com.google.gwt.core.ext.UnableToCompleteException; -import com.google.gwt.core.ext.typeinfo.JClassType; -import com.google.gwt.core.ext.typeinfo.JRealClassType; - -public class BlacklistTypeFilter implements TypeFilter { - - private List includeType; - private TreeLogger logger; - private List typePatterns; - private List values; - - public BlacklistTypeFilter(TreeLogger logger, PropertyOracle propertyOracle) - throws UnableToCompleteException { - this.logger = logger.branch(TreeLogger.DEBUG, - "Analyzing RPC blacklist information"); - try { - ConfigurationProperty prop - = propertyOracle.getConfigurationProperty("rpc.blacklist"); - - values = prop.getValues(); - int size = values.size(); - typePatterns = new ArrayList(size); - includeType = new ArrayList(size); - - // TODO investigate grouping multiple patterns into a single regex - for (String regex : values) { - // Patterns that don't start with [+-] are considered to be [-] - boolean include = false; - // Ignore empty regexes - if (regex.length() == 0) { - logger.log(TreeLogger.ERROR, "Got empty RPC blacklist entry"); - throw new UnableToCompleteException(); - } - char c = regex.charAt(0); - if (c == '+' || c == '-') { - regex = regex.substring(1); // skip initial character - include = (c == '+'); - } - try { - Pattern p = Pattern.compile(regex); - typePatterns.add(p); - includeType.add(include); - - logger.log(TreeLogger.DEBUG, - "Got RPC blacklist entry '" + regex + "'"); - } catch (PatternSyntaxException e) { - logger.log(TreeLogger.ERROR, - "Got malformed RPC blacklist entry '" + regex + "'"); - throw new UnableToCompleteException(); - } - } - } catch (BadPropertyValueException e) { - logger.log(TreeLogger.DEBUG, "No RPC blacklist entries present"); - } - } - - public String getName() { - return "BlacklistTypeFilter"; - } - - public boolean isAllowed(JClassType type) { - String name = getBaseTypeName(type); - // For types not handled by getBaseTypeName just return true. - if (name == null) { - return true; - } - - // Process patterns in reverse order for early exit - int size = typePatterns.size(); - for (int idx = size - 1; idx >= 0; idx--) { - logger.log(TreeLogger.DEBUG, "Considering RPC rule " + values.get(idx) - + " for type " + name); - boolean include = includeType.get(idx); - Pattern pattern = typePatterns.get(idx); - if (pattern.matcher(name).matches()) { - if (include) { - logger.log(TreeLogger.DEBUG, "Whitelisting type " + name - + " according to rule " + values.get(idx)); - return true; - } else { - logger.log(TreeLogger.DEBUG, "Blacklisting type " + name - + " according to rule " + values.get(idx)); - return false; - } - } - } - - // Type does not match any pattern, pass it through - return true; - } - - /** - * Returns a simple qualified name for simple types, including classes and - * interfaces, parameterized, and raw types. Null is returned for other types - * such as arrays and type parameters (e.g., 'E' in java.util.List) because - * filtering is meaningless for such types. - */ - private String getBaseTypeName(JClassType type) { - JClassType baseType = null; - - if (type instanceof JRealClassType) { - baseType = type; - } else if (type.isParameterized() != null) { - baseType = type.isParameterized().getBaseType(); - } else if (type.isRawType() != null) { - baseType = type.isRawType(); - } - - return baseType == null ? null : baseType.getQualifiedSourceName(); - } -} - diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/CustomFieldSerializerValidator.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/CustomFieldSerializerValidator.java deleted file mode 100755 index 079e3316ec3..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/CustomFieldSerializerValidator.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright 2007 Google Inc. - * - * 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 de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc; - -import com.google.gwt.core.ext.typeinfo.JClassType; -import com.google.gwt.core.ext.typeinfo.JMethod; -import com.google.gwt.core.ext.typeinfo.JParameter; -import com.google.gwt.core.ext.typeinfo.JPrimitiveType; -import com.google.gwt.core.ext.typeinfo.JType; -import com.google.gwt.user.client.rpc.SerializationStreamReader; -import com.google.gwt.user.client.rpc.SerializationStreamWriter; - -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.List; - -/** - * Checks that a custom serializer is valid. - */ -public class CustomFieldSerializerValidator { - private static final String NO_DESERIALIZE_METHOD = "Custom Field Serializer ''{0}'' does not define a deserialize method: ''public static void deserialize({1} reader,{2} instance)''"; - private static final String NO_INSTANTIATE_METHOD = "Custom Field Serializer ''{0}'' does not define an instantiate method: ''public static {1} instantiate({2} reader)''; but ''{1}'' is not default instantiable"; - private static final String NO_SERIALIZE_METHOD = "Custom Field Serializer ''{0}'' does not define a serialize method: ''public static void serialize({1} writer,{2} instance)''"; - private static final String TOO_MANY_METHODS = "Custom Field Serializer ''{0}'' defines too many methods named ''{1}''; please define only one method with that name"; - - public static JMethod getDeserializationMethod(JClassType serializer, - JClassType serializee) { - return getMethod("deserialize", SerializationStreamReader.class.getName(), - serializer, serializee); - } - - public static JMethod getInstantiationMethod(JClassType serializer, - JClassType serializee) { - JMethod[] overloads = serializer.getOverloads("instantiate"); - for (JMethod overload : overloads) { - JParameter[] parameters = overload.getParameters(); - - if (parameters.length != 1) { - // Different overload - continue; - } - - if (!parameters[0].getType().getQualifiedSourceName().equals( - SerializationStreamReader.class.getName())) { - // First param is not a stream class - continue; - } - - if (!isValidCustomFieldSerializerMethod(overload)) { - continue; - } - - JType type = overload.getReturnType(); - if (type.isPrimitive() != null) { - // Primitives are auto serialized so this can't be the right method - continue; - } - - // TODO: if isArray answered yes to isClass this cast would not be - // necessary - JClassType clazz = (JClassType) type; - if (clazz.isAssignableFrom(serializee)) { - return overload; - } - } - - return null; - } - - public static JMethod getSerializationMethod(JClassType serializer, - JClassType serializee) { - return getMethod("serialize", SerializationStreamWriter.class.getName(), - serializer, serializee); - } - - public static boolean hasDeserializationMethod(JClassType serializer, - JClassType serializee) { - return getDeserializationMethod(serializer, serializee) != null; - } - - public static boolean hasInstantiationMethod(JClassType serializer, - JClassType serializee) { - return getInstantiationMethod(serializer, serializee) != null; - } - - public static boolean hasSerializationMethod(JClassType serializer, - JClassType serializee) { - return getSerializationMethod(serializer, serializee) != null; - } - - /** - * Returns a list of error messages associated with the custom field - * serializer. - * - * @param serializer the class which performs the serialization - * @param serializee the class being serialized - * @return list of error messages, if any, associated with the custom field - * serializer - */ - public static List validate(JClassType serializer, - JClassType serializee) { - List reasons = new ArrayList(); - - if (serializee.isEnum() != null) { - /* - * Enumerated types cannot have custom field serializers because it would - * introduce shared state between the client and the server via the - * enumerated constants. - */ - reasons.add("Enumerated types cannot have custom field serializers."); - return reasons; - } - - if (!hasDeserializationMethod(serializer, serializee)) { - // No valid deserialize method was found. - reasons.add(MessageFormat.format(NO_DESERIALIZE_METHOD, - serializer.getQualifiedSourceName(), - SerializationStreamReader.class.getName(), - serializee.getQualifiedSourceName())); - } else { - checkTooMany("deserialize", serializer, reasons); - } - - if (!hasSerializationMethod(serializer, serializee)) { - // No valid serialize method was found. - reasons.add(MessageFormat.format(NO_SERIALIZE_METHOD, - serializer.getQualifiedSourceName(), - SerializationStreamWriter.class.getName(), - serializee.getQualifiedSourceName())); - } else { - checkTooMany("serialize", serializer, reasons); - } - - if (!hasInstantiationMethod(serializer, serializee)) { - if (!serializee.isDefaultInstantiable() && !serializee.isAbstract()) { - // Not default instantiable and no instantiate method was found. - reasons.add(MessageFormat.format(NO_INSTANTIATE_METHOD, - serializer.getQualifiedSourceName(), - serializee.getQualifiedSourceName(), - SerializationStreamReader.class.getName())); - } - } else { - checkTooMany("instantiate", serializer, reasons); - } - - return reasons; - } - - private static void checkTooMany(String methodName, JClassType serializer, - List reasons) { - JMethod[] overloads = serializer.getOverloads(methodName); - if (overloads.length > 1) { - reasons.add(MessageFormat.format(TOO_MANY_METHODS, - serializer.getQualifiedSourceName(), methodName)); - } - } - - private static JMethod getMethod(String methodName, String streamClassName, - JClassType serializer, JClassType serializee) { - JMethod[] overloads = serializer.getOverloads(methodName); - for (JMethod overload : overloads) { - JParameter[] parameters = overload.getParameters(); - - if (parameters.length != 2) { - // Different overload - continue; - } - - if (!parameters[0].getType().getQualifiedSourceName().equals( - streamClassName)) { - // First param is not a stream class - continue; - } - - JParameter serializeeParam = parameters[1]; - JType type = serializeeParam.getType(); - if (type.isPrimitive() != null) { - // Primitives are auto serialized so this can't be the right method - continue; - } - - // TODO: if isArray answered yes to isClass this cast would not be - // necessary - JClassType clazz = (JClassType) type; - if (clazz.isAssignableFrom(serializee)) { - if (isValidCustomFieldSerializerMethod(overload) - && overload.getReturnType() == JPrimitiveType.VOID) { - return overload; - } - } - } - - return null; - } - - private static boolean isValidCustomFieldSerializerMethod(JMethod method) { - if (method == null) { - return false; - } - - if (!method.isStatic()) { - return false; - } - - if (!method.isPublic()) { - return false; - } - - return true; - } - - private CustomFieldSerializerValidator() { - } -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/FieldSerializerCreator.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/FieldSerializerCreator.java deleted file mode 100755 index 6fe852fe1cc..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/FieldSerializerCreator.java +++ /dev/null @@ -1,503 +0,0 @@ -/* - * Copyright 2008 Google Inc. - * - * 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 de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc; - -import java.io.PrintWriter; - -import com.google.gwt.core.client.UnsafeNativeLong; -import com.google.gwt.core.client.impl.WeakMapping; -import com.google.gwt.core.ext.GeneratorContext; -import com.google.gwt.core.ext.TreeLogger; -import com.google.gwt.core.ext.typeinfo.JArrayType; -import com.google.gwt.core.ext.typeinfo.JClassType; -import com.google.gwt.core.ext.typeinfo.JEnumType; -import com.google.gwt.core.ext.typeinfo.JField; -import com.google.gwt.core.ext.typeinfo.JPrimitiveType; -import com.google.gwt.core.ext.typeinfo.JType; -import com.google.gwt.core.ext.typeinfo.TypeOracle; -import com.google.gwt.user.client.rpc.SerializationException; -import com.google.gwt.user.client.rpc.SerializationStreamReader; -import com.google.gwt.user.client.rpc.SerializationStreamWriter; -import com.google.gwt.user.client.rpc.core.java.lang.Object_Array_CustomFieldSerializer; -import com.google.gwt.user.rebind.ClassSourceFileComposerFactory; -import com.google.gwt.user.rebind.SourceWriter; - -/** - * Creates a field serializer for a class that implements - * {@link com.google.gwt.user.client.rpc.IsSerializable IsSerializable} or - * {@link java.io.Serializable Serializable}. The field serializer is emitted - * into the same package as the class that it serializes. - * - * TODO(mmendez): Need to make the generated field serializers final - * TODO(mmendez): Would be nice to be able to have imports, rather than using - * fully qualified type names everywhere - */ -public class FieldSerializerCreator { - - private static final String WEAK_MAPPING_CLASS_NAME = WeakMapping.class.getName(); - - private final JClassType serializableClass; - - private final JField[] serializableFields; - - private SourceWriter sourceWriter; - - private final SerializableTypeOracle typesSentFromBrowser; - - private final SerializableTypeOracle typesSentToBrowser; - - private final TypeOracle typeOracle; - - /** - * Constructs a field serializer for the class. - */ - public FieldSerializerCreator(TypeOracle typeOracle, - SerializableTypeOracle typesSentFromBrowser, - SerializableTypeOracle typesSentToBrowser, JClassType requestedClass) { - assert (requestedClass != null); - assert (requestedClass.isClass() != null || requestedClass.isArray() != null); - - this.typeOracle = typeOracle; - this.typesSentFromBrowser = typesSentFromBrowser; - this.typesSentToBrowser = typesSentToBrowser; - serializableClass = requestedClass; - serializableFields = SerializationUtils.getSerializableFields(typeOracle, - requestedClass); - } - - public String realize(TreeLogger logger, GeneratorContext ctx) { - assert (ctx != null); - assert (typesSentFromBrowser.isSerializable(serializableClass) || typesSentToBrowser.isSerializable(serializableClass)); - - logger = logger.branch(TreeLogger.DEBUG, - "Generating a field serializer for type '" - + serializableClass.getQualifiedSourceName() + "'", null); - - String fieldSerializerName = SerializationUtils.getFieldSerializerName( - typeOracle, serializableClass); - - sourceWriter = getSourceWriter(logger, ctx); - if (sourceWriter == null) { - return fieldSerializerName; - } - assert sourceWriter != null; - - writeFieldAccessors(); - - writeDeserializeMethod(); - - maybeWriteInstatiateMethod(); - - writeSerializeMethod(); - - sourceWriter.commit(logger); - - return fieldSerializerName; - } - - private String createArrayInstantiationExpression(JArrayType array) { - StringBuilder sb = new StringBuilder(); - - sb.append("new "); - sb.append(array.getLeafType().getQualifiedSourceName()); - sb.append("[rank]"); - for (int i = 0; i < array.getRank() - 1; ++i) { - sb.append("[]"); - } - - return sb.toString(); - } - - /** - * Returns the depth of the given class in the class hierarchy - * (where the depth of java.lang.Object == 0). - */ - private int getDepth(JClassType clazz) { - int depth = 0; - while ((clazz = clazz.getSuperclass()) != null) { - depth++; - } - return depth; - } - - private SourceWriter getSourceWriter(TreeLogger logger, GeneratorContext ctx) { - String qualifiedSerializerName = SerializationUtils.getFieldSerializerName( - typeOracle, serializableClass); - int packageNameEnd = qualifiedSerializerName.lastIndexOf('.'); - String className; - String packageName; - if (packageNameEnd != -1) { - className = qualifiedSerializerName.substring(packageNameEnd + 1); - packageName = qualifiedSerializerName.substring(0, packageNameEnd); - } else { - className = qualifiedSerializerName; - packageName = ""; - } - - PrintWriter printWriter = ctx.tryCreate(logger, packageName, className); - if (printWriter == null) { - return null; - } - - ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory( - packageName, className); - composerFactory.addAnnotationDeclaration("@SuppressWarnings(\"deprecation\")"); - return composerFactory.createSourceWriter(ctx, printWriter); - } - - private void maybeSuppressLongWarnings(JType fieldType) { - if (fieldType == JPrimitiveType.LONG) { - /** - * Accessing long from JSNI causes a error, but field serializers need to - * be able to do just that in order to bypass java accessibility - * restrictions. - */ - sourceWriter.println("@" + UnsafeNativeLong.class.getName()); - } - } - - private void maybeWriteInstatiateMethod() { - if (serializableClass.isEnum() == null - && (serializableClass.isAbstract() || !serializableClass.isDefaultInstantiable())) { - /* - * Field serializers are shared by all of the RemoteService proxies in a - * compilation. Therefore, we have to generate an instantiate method even - * if the type is not instantiable relative to the RemoteService which - * caused this field serializer to be created. If the type is not - * instantiable relative to any of the RemoteService proxies, dead code - * optimizations will cause the method to be removed from the compiled - * output. - * - * Enumerated types require an instantiate method even if they are - * abstract. You will have an abstract enum in cases where the enum type - * is sub-classed. Non-default instantiable classes cannot have - * instantiate methods. - */ - return; - } - - JArrayType isArray = serializableClass.isArray(); - JEnumType isEnum = serializableClass.isEnum(); - boolean isNative = (isArray == null) && (isEnum == null); - - sourceWriter.print("public static" + (isNative ? " native " : " ")); - String qualifiedSourceName = serializableClass.getQualifiedSourceName(); - sourceWriter.print(qualifiedSourceName); - sourceWriter.print(" instantiate("); - sourceWriter.print(SerializationStreamReader.class.getName()); - sourceWriter.println(" streamReader) throws " - + SerializationException.class.getName() + (isNative ? "/*-{" : "{")); - sourceWriter.indent(); - - if (isArray != null) { - sourceWriter.println("int rank = streamReader.readInt();"); - sourceWriter.println("return " - + createArrayInstantiationExpression(isArray) + ";"); - } else if (isEnum != null) { - sourceWriter.println("int ordinal = streamReader.readInt();"); - sourceWriter.println(qualifiedSourceName + "[] values = " - + qualifiedSourceName + ".values();"); - sourceWriter.println("assert (ordinal >= 0 && ordinal < values.length);"); - sourceWriter.println("return values[ordinal];"); - } else { - sourceWriter.println("return @" + qualifiedSourceName + "::new()();"); - } - - sourceWriter.outdent(); - sourceWriter.println(isNative ? "}-*/;" : "}"); - sourceWriter.println(); - } - - /** - * Returns true if we will need a get/set method pair for a field. - * - * @return true if the the field requires accessor methods - */ - private boolean needsAccessorMethods(JField field) { - /* - * Field serializers are always emitted into the the same package as the - * class that they serialize. This enables the serializer class to access - * all fields except those that are private. - * - * Java Access Levels: default - package private - class only protected - - * package and all subclasses public - all - */ - return field.isPrivate(); - } - - private void writeArrayDeserializationStatements(JArrayType isArray) { - JType componentType = isArray.getComponentType(); - String readMethodName = Shared.getStreamReadMethodNameFor(componentType); - - if ("readObject".equals(readMethodName)) { - // Optimize and use the default object custom serializer... - sourceWriter.println(Object_Array_CustomFieldSerializer.class.getName() - + ".deserialize(streamReader, instance);"); - } else { - sourceWriter.println("for (int i = 0, n = instance.length; i < n; ++i) {"); - sourceWriter.indent(); - sourceWriter.print("instance[i] = streamReader."); - sourceWriter.println(readMethodName + "();"); - sourceWriter.outdent(); - sourceWriter.println("}"); - } - } - - private void writeArraySerializationStatements(JArrayType isArray) { - JType componentType = isArray.getComponentType(); - String writeMethodName = Shared.getStreamWriteMethodNameFor(componentType); - if ("writeObject".equals(writeMethodName)) { - // Optimize and use the default object custom serializer... - sourceWriter.println(Object_Array_CustomFieldSerializer.class.getName() - + ".serialize(streamWriter, instance);"); - } else { - sourceWriter.println("streamWriter.writeInt(instance.length);"); - sourceWriter.println(); - sourceWriter.println("for (int i = 0, n = instance.length; i < n; ++i) {"); - sourceWriter.indent(); - sourceWriter.print("streamWriter."); - sourceWriter.print(writeMethodName); - sourceWriter.println("(instance[i]);"); - sourceWriter.outdent(); - sourceWriter.println("}"); - } - } - - private void writeClassDeserializationStatements() { - /** - * If the type is capable of making a round trip between the client and - * server, store additional server-only field data using {@link WeakMapping}. - */ - if (serializableClass.isEnhanced()) { - sourceWriter.println(WEAK_MAPPING_CLASS_NAME + ".set(instance, " - + "\"server-enhanced-data-" - + getDepth(serializableClass) - + "\", streamReader.readString());"); - } - - for (JField serializableField : serializableFields) { - JType fieldType = serializableField.getType(); - - String readMethodName = Shared.getStreamReadMethodNameFor(fieldType); - String streamReadExpression = "streamReader." + readMethodName + "()"; - if (Shared.typeNeedsCast(fieldType)) { - streamReadExpression = "(" + fieldType.getQualifiedSourceName() + ") " - + streamReadExpression; - } - - if (needsAccessorMethods(serializableField)) { - sourceWriter.print("set"); - sourceWriter.print(Shared.capitalize(serializableField.getName())); - sourceWriter.print("(instance, "); - sourceWriter.print(streamReadExpression); - sourceWriter.println(");"); - } else { - sourceWriter.print("instance."); - sourceWriter.print(serializableField.getName()); - sourceWriter.print(" = "); - sourceWriter.print(streamReadExpression); - sourceWriter.println(";"); - } - } - - sourceWriter.println(); - - JClassType superClass = serializableClass.getSuperclass(); - if (superClass != null - && (typesSentFromBrowser.isSerializable(superClass) || typesSentToBrowser.isSerializable(superClass))) { - String fieldSerializerName = SerializationUtils.getFieldSerializerName( - typeOracle, superClass); - sourceWriter.print(fieldSerializerName); - sourceWriter.println(".deserialize(streamReader, instance);"); - } - } - - private void writeClassSerializationStatements() { - /** - * If the type is capable of making a round trip between the client and - * server, retrieve the additional server-only field data from {@link WeakMapping}. - */ - - if (serializableClass.isEnhanced()) { - sourceWriter.println("streamWriter.writeString((String) " - + WEAK_MAPPING_CLASS_NAME - + ".get(instance, \"server-enhanced-data-" - + getDepth(serializableClass) + "\"));"); - } - - for (JField serializableField : serializableFields) { - JType fieldType = serializableField.getType(); - - String writeMethodName = Shared.getStreamWriteMethodNameFor(fieldType); - sourceWriter.print("streamWriter."); - sourceWriter.print(writeMethodName); - sourceWriter.print("("); - - if (needsAccessorMethods(serializableField)) { - sourceWriter.print("get"); - sourceWriter.print(Shared.capitalize(serializableField.getName())); - sourceWriter.println("(instance));"); - } else { - sourceWriter.print("instance."); - sourceWriter.print(serializableField.getName()); - sourceWriter.println(");"); - } - } - - sourceWriter.println(); - - JClassType superClass = serializableClass.getSuperclass(); - if (superClass != null - && (typesSentFromBrowser.isSerializable(superClass) || typesSentToBrowser.isSerializable(superClass))) { - String fieldSerializerName = SerializationUtils.getFieldSerializerName( - typeOracle, superClass); - sourceWriter.print(fieldSerializerName); - sourceWriter.println(".serialize(streamWriter, instance);"); - } - } - - private void writeDeserializeMethod() { - sourceWriter.print("public static void deserialize("); - sourceWriter.print(SerializationStreamReader.class.getName()); - sourceWriter.print(" streamReader, "); - sourceWriter.print(serializableClass.getQualifiedSourceName()); - sourceWriter.println(" instance) throws " - + SerializationException.class.getName() + "{"); - sourceWriter.indent(); - - JArrayType isArray = serializableClass.isArray(); - if (isArray != null) { - writeArrayDeserializationStatements(isArray); - } else if (serializableClass.isEnum() != null) { - writeEnumDeserializationStatements(); - } else { - writeClassDeserializationStatements(); - } - - sourceWriter.outdent(); - sourceWriter.println("}"); - sourceWriter.println(); - } - - private void writeEnumDeserializationStatements() { - sourceWriter.println("// Enum deserialization is handled via the instantiate method"); - } - - private void writeEnumSerializationStatements() { - sourceWriter.println("assert (instance != null);"); - sourceWriter.println("streamWriter.writeInt(instance.ordinal());"); - } - - /** - * This method will generate a native JSNI accessor method for every field - * that is protected, private using the "Violator" pattern to allow an - * external class to access the field's value. - */ - private void writeFieldAccessors() { - for (JField serializableField : serializableFields) { - if (!needsAccessorMethods(serializableField)) { - continue; - } - - writeFieldGet(serializableField); - writeFieldSet(serializableField); - } - } - - /** - * Write a getter method for an instance field. - */ - private void writeFieldGet(JField serializableField) { - JType fieldType = serializableField.getType(); - String fieldTypeQualifiedSourceName = fieldType.getQualifiedSourceName(); - String fieldName = serializableField.getName(); - - maybeSuppressLongWarnings(fieldType); - sourceWriter.print("private static native "); - sourceWriter.print(fieldTypeQualifiedSourceName); - sourceWriter.print(" get"); - sourceWriter.print(Shared.capitalize(fieldName)); - sourceWriter.print("("); - sourceWriter.print(serializableClass.getQualifiedSourceName()); - sourceWriter.println(" instance) /*-{"); - sourceWriter.indent(); - - sourceWriter.print("return instance.@"); - sourceWriter.print(serializableClass.getQualifiedBinaryName()); - sourceWriter.print("::"); - sourceWriter.print(fieldName); - sourceWriter.println(";"); - - sourceWriter.outdent(); - sourceWriter.println("}-*/;"); - sourceWriter.println(); - } - - /** - * Write a setter method for an instance field. - */ - private void writeFieldSet(JField serializableField) { - JType fieldType = serializableField.getType(); - String fieldTypeQualifiedSourceName = fieldType.getQualifiedSourceName(); - String serializableClassQualifedName = serializableClass.getQualifiedSourceName(); - String fieldName = serializableField.getName(); - - maybeSuppressLongWarnings(fieldType); - sourceWriter.print("private static native void "); - sourceWriter.print(" set"); - sourceWriter.print(Shared.capitalize(fieldName)); - sourceWriter.print("("); - sourceWriter.print(serializableClassQualifedName); - sourceWriter.print(" instance, "); - sourceWriter.print(fieldTypeQualifiedSourceName); - sourceWriter.println(" value) /*-{"); - sourceWriter.indent(); - - sourceWriter.print("instance.@"); - sourceWriter.print(serializableClass.getQualifiedBinaryName()); - sourceWriter.print("::"); - sourceWriter.print(fieldName); - sourceWriter.println(" = value;"); - - sourceWriter.outdent(); - sourceWriter.println("}-*/;"); - sourceWriter.println(); - } - - private void writeSerializeMethod() { - sourceWriter.print("public static void serialize("); - sourceWriter.print(SerializationStreamWriter.class.getName()); - sourceWriter.print(" streamWriter, "); - sourceWriter.print(serializableClass.getQualifiedSourceName()); - sourceWriter.println(" instance) throws " - + SerializationException.class.getName() + " {"); - sourceWriter.indent(); - - JArrayType isArray = serializableClass.isArray(); - if (isArray != null) { - writeArraySerializationStatements(isArray); - } else if (serializableClass.isEnum() != null) { - writeEnumSerializationStatements(); - } else { - writeClassSerializationStatements(); - } - - sourceWriter.outdent(); - sourceWriter.println("}"); - sourceWriter.println(); - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/JModTypeVisitor.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/JModTypeVisitor.java deleted file mode 100755 index d1dad0331ac..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/JModTypeVisitor.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright 2008 Google Inc. - * - * 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 de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc; - -import com.google.gwt.core.ext.typeinfo.JArrayType; -import com.google.gwt.core.ext.typeinfo.JClassType; -import com.google.gwt.core.ext.typeinfo.JGenericType; -import com.google.gwt.core.ext.typeinfo.JParameterizedType; -import com.google.gwt.core.ext.typeinfo.JPrimitiveType; -import com.google.gwt.core.ext.typeinfo.JRawType; -import com.google.gwt.core.ext.typeinfo.JType; -import com.google.gwt.core.ext.typeinfo.JWildcardType; - -/** - *

- * This visitor supports transforming interior parts of a type. Subclasses - * should override the appropriate endVisit methods and, when - * such a method wants to replace its argument, assign the replacement to the - * field {@link #replacement}. - *

- * - *

- * Any specified replacements must be sensible no matter what context they might - * be used in. Specifically: - *

- *
    - *
  • Primitive types may only be replaced by primitive types. - *
  • Reference types may only be replaced by reference types. - *
  • Generic types may only be replaced by generic types, and the replacement - * should have the same number of type parameters as the original. - *
- */ -class JModTypeVisitor extends JTypeVisitor { - /** - * A subclass's endVisit method can indicate that it wants to - * replace its argument by assigning the replacement to this field. - */ - protected JType replacement; - - @Override - public void accept(JType type) { - replacement = type; - acceptChildren(type); - endVisit(replacement); - } - - public JClassType transform(JClassType type) { - // transforming a class type should give a class type back - return (JClassType) transform((JType) type); - } - - public JGenericType transform(JGenericType type) { - // transforming a generic type should give a generic type back - return (JGenericType) transform((JType) type); - } - - public JPrimitiveType transform(JPrimitiveType type) { - // transforming a primitive type should give a primitive type back - return (JPrimitiveType) transform((JType) type); - } - - public JType transform(JType type) { - accept(type); - return replacement; - } - - /** - * Do the same thing as {@link JTypeVisitor#acceptChildren(JType)}, but if - * any children types are replaced, reconstruct a version of type - * that has those corresponding replacements made and assign the new type to - * {@link #replacement}. - */ - @Override - protected void acceptChildren(JType type) { - JArrayType typeArray = type.isArray(); - if (typeArray != null) { - JType oldComponentType = typeArray.getComponentType(); - JType newComponentType = transform(oldComponentType); - - if (oldComponentType == newComponentType) { - replacement = type; - } else { - replacement = typeArray.getOracle().getArrayType(newComponentType); - } - } - - JParameterizedType typeParameterized = type.isParameterized(); - if (typeParameterized != null) { - JGenericType oldBaseType = typeParameterized.getBaseType(); - JGenericType newBaseType = transform(oldBaseType); - - JClassType oldEnclosingType = typeParameterized.getEnclosingType(); - JClassType newEnclosingType = oldEnclosingType == null ? null - : transform(oldEnclosingType); - - JClassType[] oldTypeArgs = typeParameterized.getTypeArgs(); - JClassType[] newTypeArgs = new JClassType[oldTypeArgs.length]; - boolean argsAllSame = true; - for (int i = 0; i < oldTypeArgs.length; i++) { - newTypeArgs[i] = transform(oldTypeArgs[i]); - if (newTypeArgs[i] != oldTypeArgs[i]) { - argsAllSame = false; - } - } - - if (argsAllSame && oldBaseType == newBaseType - && oldEnclosingType == newEnclosingType) { - replacement = type; - } else { - replacement = typeParameterized.getOracle().getParameterizedType( - newBaseType, newEnclosingType, newTypeArgs); - } - } - - JRawType typeRaw = type.isRawType(); - if (typeRaw != null) { - JGenericType oldBaseType = typeRaw.getBaseType(); - JGenericType newBaseType = transform(oldBaseType); - - if (oldBaseType == newBaseType) { - replacement = type; - } else { - replacement = newBaseType.getRawType(); - } - } - - JWildcardType typeWild = type.isWildcard(); - if (typeWild != null) { - JClassType oldBound = typeWild.getFirstBound(); - JClassType newBound = transform(oldBound); - - if (oldBound == newBound) { - replacement = type; - } else { - replacement = typeWild.getOracle().getWildcardType( - typeWild.getBoundType(), newBound); - } - } - } -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/JTypeVisitor.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/JTypeVisitor.java deleted file mode 100755 index c336e454933..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/JTypeVisitor.java +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Copyright 2008 Google Inc. - * - * 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 de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc; - -import com.google.gwt.core.ext.typeinfo.JAnnotationType; -import com.google.gwt.core.ext.typeinfo.JArrayType; -import com.google.gwt.core.ext.typeinfo.JClassType; -import com.google.gwt.core.ext.typeinfo.JEnumType; -import com.google.gwt.core.ext.typeinfo.JGenericType; -import com.google.gwt.core.ext.typeinfo.JParameterizedType; -import com.google.gwt.core.ext.typeinfo.JPrimitiveType; -import com.google.gwt.core.ext.typeinfo.JRawType; -import com.google.gwt.core.ext.typeinfo.JRealClassType; -import com.google.gwt.core.ext.typeinfo.JType; -import com.google.gwt.core.ext.typeinfo.JTypeParameter; -import com.google.gwt.core.ext.typeinfo.JWildcardType; - -/** - * A visitor that traverses the structure of a {@link JType}. - */ -class JTypeVisitor { - /** - * Accept type, traverse its children with - * {@link #acceptChildren(JType)}, and then call {@link #endVisit(JType)} on - * type itself. - */ - public void accept(JType type) { - acceptChildren(type); - endVisit(type); - } - - /** - * Call {@link #accept(JType)} on all children types of type. - * The children type of a type are its structural components. For example, an - * array type has one child, which is the component type of the array. - */ - protected void acceptChildren(JType type) { - JArrayType typeArray = type.isArray(); - if (typeArray != null) { - accept(typeArray.getComponentType()); - endVisit(typeArray); - } - - JParameterizedType typeParameterized = type.isParameterized(); - if (typeParameterized != null) { - accept(typeParameterized.getBaseType()); - for (JClassType typeArg : typeParameterized.getTypeArgs()) { - accept(typeArg); - } - endVisit(typeParameterized); - } - - JRawType typeRaw = type.isRawType(); - if (typeRaw != null) { - accept(typeRaw.getBaseType()); - endVisit(typeRaw); - } - - JWildcardType typeWild = type.isWildcard(); - if (typeWild != null) { - accept(typeWild.getFirstBound()); - endVisit(typeWild); - } - } - - /** - * @param typeAnnotation - */ - protected void endVisit(JAnnotationType typeAnnotation) { - } - - /** - * @param typeArray - */ - protected void endVisit(JArrayType typeArray) { - } - - /** - * @param typeEnum - */ - protected void endVisit(JEnumType typeEnum) { - } - - /** - * @param typeGeneric - */ - protected void endVisit(JGenericType typeGeneric) { - } - - /** - * @param typeParameterized - */ - protected void endVisit(JParameterizedType typeParameterized) { - } - - /** - * @param typePrimitive - */ - protected void endVisit(JPrimitiveType typePrimitive) { - } - - /** - * @param typeRaw - */ - protected void endVisit(JRawType typeRaw) { - } - - /** - * @param typeReal - */ - protected void endVisit(JRealClassType typeReal) { - } - - /** - * This endVisit is called on all visited types. By default it dispatches to - * one of the more specific endVisit methods, e.g. - * {@link #endVisit(JArrayType)}. - */ - protected void endVisit(JType type) { - JAnnotationType typeAnnotation = type.isAnnotation(); - if (typeAnnotation != null) { - endVisit(typeAnnotation); - return; - } - - JArrayType typeArray = type.isArray(); - if (typeArray != null) { - endVisit(typeArray); - return; - } - - JEnumType typeEnum = type.isEnum(); - if (typeEnum != null) { - endVisit(typeEnum); - return; - } - - JGenericType typeGeneric = type.isGenericType(); - if (typeGeneric != null) { - endVisit(typeGeneric); - return; - } - - JParameterizedType typeParameterized = type.isParameterized(); - if (typeParameterized != null) { - endVisit(typeParameterized); - return; - } - - JPrimitiveType typePrimitive = type.isPrimitive(); - if (typePrimitive != null) { - endVisit(typePrimitive); - return; - } - - JRawType typeRaw = type.isRawType(); - if (typeRaw != null) { - endVisit(typeRaw); - return; - } - - JTypeParameter typeParam = type.isTypeParameter(); - if (typeParam != null) { - endVisit(typeParam); - return; - } - - JWildcardType typeWild = type.isWildcard(); - if (typeWild != null) { - endVisit(typeWild); - return; - } - - JRealClassType typeReal = (JRealClassType) type; - endVisit(typeReal); - } - - /** - * @param typeParam - */ - protected void endVisit(JTypeParameter typeParam) { - } - - /** - * @param typeWild - */ - protected void endVisit(JWildcardType typeWild) { - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/ProblemReport.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/ProblemReport.java deleted file mode 100755 index c323c6b867d..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/ProblemReport.java +++ /dev/null @@ -1,269 +0,0 @@ -/* - * Copyright 2008 Google Inc. - * - * 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 de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc; - -import com.google.gwt.core.ext.TreeLogger; -import com.google.gwt.core.ext.TreeLogger.Type; -import com.google.gwt.core.ext.typeinfo.JClassType; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -/** - * A collection of reported problems; these are accumulated during the - * SerializableTypeOracleBuilder's isSerializable analysis, and what to do about - * the problems is decided only later. - */ -public class ProblemReport { - - /** - * Priority of problems. {@link #FATAL} problems will fail a build that - * would otherwise have succeeded, for example because of a bad custom - * serializer used only as a subclass of a superclass with other viable - * subtypes. {@link #DEFAULT} problems might or might not be fatal, - * depending on overall results accumulated later. {@link #AUXILIARY} - * problems are not fatal, and often not even problems by themselves, but - * diagnostics related to default problems (e.g. type filtration, which - * might suppress an intended-to-serialize class). - */ - public enum Priority { FATAL, DEFAULT, AUXILIARY} - - /** - * An individual report, which may require multiple entries (expressed as - * logs under a branchpoint), but relates to an individual issue. - */ - public static class Problem { - private String message; - private List childMessages; - - private Problem(String message, String[] children) { - this.message = message; - // most problems don't have sub-messages, so init at zero size - childMessages = new ArrayList(children.length); - for (int i = 0; i < children.length; i++) { - childMessages.add(children[i]); - } - } - - public void addChild(String message) { - childMessages.add(message); - } - - public String getPrimaryMessage() { - return message; - } - - public Iterable getSubMessages() { - return childMessages; - } - - public boolean hasSubMessages() { - return !childMessages.isEmpty(); - } - } - - private Map> allProblems; - private Map> auxiliaries; - private Map> fatalProblems; - private JClassType contextType; - - /** - * Creates a new, empty, context-less ProblemReport. - */ - public ProblemReport() { - Comparator comparator = new Comparator() { - public int compare(JClassType o1, JClassType o2) { - assert o1 != null; - assert o2 != null; - return o1.getParameterizedQualifiedSourceName().compareTo( - o2.getParameterizedQualifiedSourceName()); - } - }; - allProblems = new TreeMap>(comparator); - auxiliaries = new TreeMap>(comparator); - fatalProblems = new TreeMap>(comparator); - contextType = null; - } - - /** - * Adds a problem for a given type. This also sorts the problems into - * collections by priority. - * - * @param type the problematic type - * @param message the description of the problem - * @param priority priority of the problem. - * @param extraLines additional continuation lines for the message, usually - * for additional explanations. - */ - public Problem add(JClassType type, String message, Priority priority, - String... extraLines) { - String contextString = ""; - if (contextType != null) { - contextString = " (reached via " + - contextType.getParameterizedQualifiedSourceName() + ")"; - } - message = message + contextString; - Problem entry = new Problem(message, extraLines); - if (priority == Priority.AUXILIARY) { - addToMap(type, entry, auxiliaries); - return entry; - } - - // both FATAL and DEFAULT problems go in allProblems... - addToMap(type, entry, allProblems); - - // only FATAL problems go in fatalProblems... - if (priority == Priority.FATAL) { - addToMap(type, entry, fatalProblems); - } - return entry; - } - - public String getWorstMessageForType(JClassType type) { - List list = fatalProblems.get(type); - if (list == null) { - list = allProblems.get(type); - if (list == null) { - list = auxiliaries.get(type); - } - } - if (list == null) { - return null; - } - return list.get(0).getPrimaryMessage() + (list.size() > 1 ? ", etc." : ""); - } - - /** - * Were any problems reported as "fatal"? - */ - public boolean hasFatalProblems() { - return !fatalProblems.isEmpty(); - } - - /** - * Reports all problems to the logger supplied, at the log level supplied. - * The problems are assured of being reported in lexographic order of - * type names. - * - * @param logger logger to receive problem reports - * @param problemLevel severity level at which to report problems. - * @param auxLevel severity level at which to report any auxiliary messages. - */ - public void report(TreeLogger logger, TreeLogger.Type problemLevel, - TreeLogger.Type auxLevel) { - doReport(logger, auxLevel, auxiliaries); - doReport(logger, problemLevel, allProblems); - } - - /** - * Reports only urgent problems to the logger supplied, at the log level - * supplied. The problems are assured of being reported in lexographic - * order of type names. - * - * @param logger logger to receive problem reports - * @param level severity level at which to report problems. - */ - public void reportFatalProblems(TreeLogger logger, TreeLogger.Type level) { - doReport(logger, level, fatalProblems); - } - - /** - * Sets the context type currently being analyzed. Problems found will - * include reference to this context, until reset with another call to this - * method. Context may be cancelled with a {@code null} value here. - * - * @param newContext the type under analysis - */ - public void setContextType(JClassType newContext) { - contextType = newContext; - } - - /** - * Test accessor returning list of auxiliary "problems" logged against a - * given type. - * - * @param type type to fetch problems for - * @return {@code null} if no auxiliaries were logged. Otherwise, a list - * of strings describing messages, including the context in which the - * problem was found. - */ - List getAuxiliaryMessagesForType(JClassType type) { - List list = auxiliaries.get(type); - if (list == null) { - list = new ArrayList(0); - } - return list; - } - - /** - * Test accessor returning list of problems logged against a given type. - * - * @param type type to fetch problems for - * @return {@code null} if no problems were logged. Otherwise, a list - * of strings describing problems, including the context in which the - * problem was found. - */ - List getProblemsForType(JClassType type) { - List list = allProblems.get(type); - if (list == null) { - list = new ArrayList(0); - } - return list; - } - - /** - * Adds an entry to one of the problem maps. - * - * @param type the type to add - * @param message the message to add for {@code type} - * @param map the map to add to - */ - private void addToMap(JClassType type, Problem problem, - Map> map) { - List list = map.get(type); - if (list == null) { - list = new ArrayList(); - map.put(type, list); - } - list.add(problem); - } - - /** - * Logs all of the problems from one of the problem maps. - * - * @param logger the logger to log to - * @param level the level for messages - * @param problems the problems to log - */ - private void doReport(TreeLogger logger, Type level, - Map> problems) { - for (List problemList : problems.values()) { - for (Problem problem : problemList) { - if (problem.hasSubMessages()) { - TreeLogger sublogger = logger.branch(level, problem.getPrimaryMessage()); - for (String sub : problem.getSubMessages()) { - sublogger.log(level, sub); - } - } else { - logger.log(level, problem.getPrimaryMessage()); - } - } - } - } -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/ProxyCreator.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/ProxyCreator.java deleted file mode 100755 index 8348c2dc9c0..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/ProxyCreator.java +++ /dev/null @@ -1,775 +0,0 @@ -/* - * Copyright 2008 Google Inc. - * - * 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 de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.UnsupportedEncodingException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import com.google.gwt.core.client.GWT; -import com.google.gwt.core.client.impl.Impl; -import com.google.gwt.core.ext.BadPropertyValueException; -import com.google.gwt.core.ext.ConfigurationProperty; -import com.google.gwt.core.ext.GeneratorContext; -import com.google.gwt.core.ext.PropertyOracle; -import com.google.gwt.core.ext.TreeLogger; -import com.google.gwt.core.ext.UnableToCompleteException; -import com.google.gwt.core.ext.linker.EmittedArtifact.Visibility; -import com.google.gwt.core.ext.linker.GeneratedResource; -import com.google.gwt.core.ext.typeinfo.JClassType; -import com.google.gwt.core.ext.typeinfo.JField; -import com.google.gwt.core.ext.typeinfo.JMethod; -import com.google.gwt.core.ext.typeinfo.JPackage; -import com.google.gwt.core.ext.typeinfo.JParameter; -import com.google.gwt.core.ext.typeinfo.JParameterizedType; -import com.google.gwt.core.ext.typeinfo.JPrimitiveType; -import com.google.gwt.core.ext.typeinfo.JType; -import com.google.gwt.core.ext.typeinfo.NotFoundException; -import com.google.gwt.core.ext.typeinfo.TypeOracle; -import com.google.gwt.dev.generator.NameFactory; -import com.google.gwt.dev.util.Util; -import com.google.gwt.http.client.Request; -import com.google.gwt.http.client.RequestBuilder; -import com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException; -import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; -import com.google.gwt.user.client.rpc.SerializationException; -import com.google.gwt.user.client.rpc.SerializationStreamWriter; -import com.google.gwt.user.client.rpc.impl.ClientSerializationStreamWriter; -import com.google.gwt.user.client.rpc.impl.FailedRequest; -import com.google.gwt.user.client.rpc.impl.FailingRequestBuilder; -import com.google.gwt.user.client.rpc.impl.RemoteServiceProxy; -import com.google.gwt.user.client.rpc.impl.RequestCallbackAdapter.ResponseReader; -import com.google.gwt.user.linker.rpc.RpcPolicyFileArtifact; -import com.google.gwt.user.rebind.ClassSourceFileComposerFactory; -import com.google.gwt.user.rebind.SourceWriter; -import com.google.gwt.user.server.rpc.SerializationPolicyLoader; -import com.google.gwt.user.server.rpc.impl.TypeNameObfuscator; - -/** - * Creates a client-side proxy for a - * {@link com.google.gwt.user.client.rpc.RemoteService RemoteService} interface - * as well as the necessary type and field serializers. - */ -public class ProxyCreator { - - private static final Map JPRIMITIVETYPE_TO_RESPONSEREADER = new HashMap(); - - private static final String PROXY_SUFFIX = "_Proxy"; - - /** - * Adds a root type for each type that appears in the RemoteService interface - * methods. - */ - private static void addRemoteServiceRootTypes(TreeLogger logger, - TypeOracle typeOracle, - SerializableTypeOracleBuilder typesSentFromBrowser, - SerializableTypeOracleBuilder typesSentToBrowser, JClassType remoteService) - throws NotFoundException { - logger = logger.branch(TreeLogger.DEBUG, "Analyzing '" - + remoteService.getParameterizedQualifiedSourceName() - + "' for serializable types", null); - - JMethod[] methods = remoteService.getOverridableMethods(); - - JClassType exceptionClass = typeOracle.getType(Exception.class.getName()); - - TreeLogger validationLogger = logger.branch(TreeLogger.DEBUG, - "Analyzing methods:", null); - for (JMethod method : methods) { - TreeLogger methodLogger = validationLogger.branch(TreeLogger.DEBUG, - method.toString(), null); - JType returnType = method.getReturnType(); - if (returnType != JPrimitiveType.VOID) { - TreeLogger returnTypeLogger = methodLogger.branch(TreeLogger.DEBUG, - "Return type: " + returnType.getParameterizedQualifiedSourceName(), - null); - typesSentToBrowser.addRootType(returnTypeLogger, returnType); - } - - JParameter[] params = method.getParameters(); - for (JParameter param : params) { - TreeLogger paramLogger = methodLogger.branch(TreeLogger.DEBUG, - "Parameter: " + param.toString(), null); - JType paramType = param.getType(); - typesSentFromBrowser.addRootType(paramLogger, paramType); - } - - JType[] exs = method.getThrows(); - if (exs.length > 0) { - TreeLogger throwsLogger = methodLogger.branch(TreeLogger.DEBUG, - "Throws:", null); - for (JType ex : exs) { - if (!exceptionClass.isAssignableFrom(ex.isClass())) { - throwsLogger = throwsLogger.branch( - TreeLogger.WARN, - "'" - + ex.getQualifiedSourceName() - + "' is not a checked exception; only checked exceptions may be used", - null); - } - - typesSentToBrowser.addRootType(throwsLogger, ex); - } - } - } - } - - /** - * Add the implicit root types that are needed to make RPC work. These would - * be {@link String} and {@link IncompatibleRemoteServiceException}. - */ - private static void addRequiredRoots(TreeLogger logger, - TypeOracle typeOracle, SerializableTypeOracleBuilder stob) - throws NotFoundException { - logger = logger.branch(TreeLogger.DEBUG, "Analyzing implicit types"); - - // String is always instantiable. - JClassType stringType = typeOracle.getType(String.class.getName()); - stob.addRootType(logger, stringType); - - // IncompatibleRemoteServiceException is always serializable - JClassType icseType = typeOracle.getType(IncompatibleRemoteServiceException.class.getName()); - stob.addRootType(logger, icseType); - } - - /** - * Take the union of two type arrays, and then sort the results - * alphabetically. - */ - private static JType[] unionOfTypeArrays(JType[]... types) { - Set typesList = new HashSet(); - for (JType[] a : types) { - typesList.addAll(Arrays.asList(a)); - } - JType[] serializableTypes = typesList.toArray(new JType[0]); - Arrays.sort(serializableTypes, - SerializableTypeOracleBuilder.JTYPE_COMPARATOR); - return serializableTypes; - } - - protected JClassType serviceIntf; - - private boolean elideTypeNames; - - /** - * The possibly obfuscated type signatures used to represent a type. - */ - private Map typeStrings; - - { - JPRIMITIVETYPE_TO_RESPONSEREADER.put(JPrimitiveType.BOOLEAN, - ResponseReader.BOOLEAN); - JPRIMITIVETYPE_TO_RESPONSEREADER.put(JPrimitiveType.BYTE, - ResponseReader.BYTE); - JPRIMITIVETYPE_TO_RESPONSEREADER.put(JPrimitiveType.CHAR, - ResponseReader.CHAR); - JPRIMITIVETYPE_TO_RESPONSEREADER.put(JPrimitiveType.DOUBLE, - ResponseReader.DOUBLE); - JPRIMITIVETYPE_TO_RESPONSEREADER.put(JPrimitiveType.FLOAT, - ResponseReader.FLOAT); - JPRIMITIVETYPE_TO_RESPONSEREADER.put(JPrimitiveType.INT, ResponseReader.INT); - JPRIMITIVETYPE_TO_RESPONSEREADER.put(JPrimitiveType.LONG, - ResponseReader.LONG); - JPRIMITIVETYPE_TO_RESPONSEREADER.put(JPrimitiveType.SHORT, - ResponseReader.SHORT); - JPRIMITIVETYPE_TO_RESPONSEREADER.put(JPrimitiveType.VOID, - ResponseReader.VOID); - } - - public ProxyCreator(JClassType serviceIntf) { - assert (serviceIntf.isInterface() != null); - this.serviceIntf = serviceIntf; - } - - /** - * Creates the client-side proxy class. - * - * @throws UnableToCompleteException - */ - public String create(TreeLogger logger, GeneratorContext context) - throws UnableToCompleteException { - TypeOracle typeOracle = context.getTypeOracle(); - - JClassType serviceAsync = typeOracle.findType(serviceIntf.getQualifiedSourceName() - + "Async"); - if (serviceAsync == null) { - logger.branch(TreeLogger.ERROR, - "Could not find an asynchronous version for the service interface " - + serviceIntf.getQualifiedSourceName(), null); - RemoteServiceAsyncValidator.logValidAsyncInterfaceDeclaration(logger, - serviceIntf); - throw new UnableToCompleteException(); - } - - SourceWriter srcWriter = getSourceWriter(logger, context, serviceAsync); - if (srcWriter == null) { - return getProxyQualifiedName(); - } - - // Make sure that the async and synchronous versions of the RemoteService - // agree with one another - // - RemoteServiceAsyncValidator rsav = new RemoteServiceAsyncValidator(logger, - typeOracle); - Map syncMethToAsyncMethMap = rsav.validate(logger, - serviceIntf, serviceAsync); - - final PropertyOracle propertyOracle = context.getPropertyOracle(); - - // Load the blacklist/whitelist - TypeFilter blacklistTypeFilter = new BlacklistTypeFilter(logger, - propertyOracle); - - // Determine the set of serializable types - SerializableTypeOracleBuilder typesSentFromBrowserBuilder = new SerializableTypeOracleBuilder( - logger, propertyOracle, typeOracle); - typesSentFromBrowserBuilder.setTypeFilter(blacklistTypeFilter); - SerializableTypeOracleBuilder typesSentToBrowserBuilder = new SerializableTypeOracleBuilder( - logger, propertyOracle, typeOracle); - typesSentToBrowserBuilder.setTypeFilter(blacklistTypeFilter); - - addRoots(logger, typeOracle, typesSentFromBrowserBuilder, - typesSentToBrowserBuilder); - - try { - ConfigurationProperty prop = context.getPropertyOracle().getConfigurationProperty( - TypeSerializerCreator.GWT_ELIDE_TYPE_NAMES_FROM_RPC); - elideTypeNames = Boolean.parseBoolean(prop.getValues().get(0)); - } catch (BadPropertyValueException e) { - logger.log(TreeLogger.ERROR, "Configuration property " - + TypeSerializerCreator.GWT_ELIDE_TYPE_NAMES_FROM_RPC - + " is not defined. Is RemoteService.gwt.xml inherited?"); - throw new UnableToCompleteException(); - } - - // Create a resource file to receive all of the serialization information - // computed by STOB and mark it as private so it does not end up in the - // output. - OutputStream pathInfo = context.tryCreateResource(logger, - serviceIntf.getQualifiedSourceName() + ".rpc.log"); - PrintWriter writer = null; - SerializableTypeOracle typesSentFromBrowser; - SerializableTypeOracle typesSentToBrowser; - try { - writer = new PrintWriter(pathInfo); - - typesSentFromBrowserBuilder.setLogOutputStream(pathInfo); - typesSentToBrowserBuilder.setLogOutputStream(pathInfo); - - writer.write("====================================\n"); - writer.write("Types potentially sent from browser:\n"); - writer.write("====================================\n\n"); - writer.flush(); - typesSentFromBrowser = typesSentFromBrowserBuilder.build(logger); - - writer.write("===================================\n"); - writer.write("Types potentially sent from server:\n"); - writer.write("===================================\n\n"); - writer.flush(); - typesSentToBrowser = typesSentToBrowserBuilder.build(logger); - - if (pathInfo != null) { - context.commitResource(logger, pathInfo).setVisibility(Visibility.Private); - } - } finally { - if (writer != null) { - writer.close(); - } - } - - generateTypeHandlers(logger, context, typesSentFromBrowser, - typesSentToBrowser); - - String serializationPolicyStrongName = writeSerializationPolicyFile(logger, - context, typesSentFromBrowser, typesSentToBrowser); - - String remoteServiceInterfaceName = elideTypeNames - ? TypeNameObfuscator.SERVICE_INTERFACE_ID - : serviceIntf.getQualifiedBinaryName(); - generateProxyFields(srcWriter, typesSentFromBrowser, - serializationPolicyStrongName, remoteServiceInterfaceName); - - generateProxyContructor(srcWriter); - - generateProxyMethods(srcWriter, typesSentFromBrowser, - syncMethToAsyncMethMap); - - if (elideTypeNames) { - generateStreamWriterOverride(srcWriter); - } - - srcWriter.commit(logger); - - return getProxyQualifiedName(); - } - - protected void addRoots(TreeLogger logger, TypeOracle typeOracle, - SerializableTypeOracleBuilder typesSentFromBrowserBuilder, - SerializableTypeOracleBuilder typesSentToBrowserBuilder) - throws UnableToCompleteException { - try { - addRequiredRoots(logger, typeOracle, typesSentFromBrowserBuilder); - addRequiredRoots(logger, typeOracle, typesSentToBrowserBuilder); - - addRemoteServiceRootTypes(logger, typeOracle, - typesSentFromBrowserBuilder, typesSentToBrowserBuilder, serviceIntf); - } catch (NotFoundException e) { - logger.log(TreeLogger.ERROR, - "Unable to find type referenced from remote service", e); - throw new UnableToCompleteException(); - } - } - - protected String computeTypeNameExpression(JType paramType) { - String typeName; - if (typeStrings.containsKey(paramType)) { - typeName = typeStrings.get(paramType); - } else { - typeName = paramType.getQualifiedBinaryName(); - } - return typeName == null ? null : ('"' + typeName + '"'); - } - - /** - * Generate the proxy constructor and delegate to the superclass constructor - * using the default address for the - * {@link com.google.gwt.user.client.rpc.RemoteService RemoteService}. - */ - protected void generateProxyContructor(SourceWriter srcWriter) { - srcWriter.println("public " + getProxySimpleName() + "() {"); - srcWriter.indent(); - srcWriter.println("super(GWT.getModuleBaseURL(),"); - srcWriter.indent(); - srcWriter.println(getRemoteServiceRelativePath() + ", "); - srcWriter.println("SERIALIZATION_POLICY, "); - srcWriter.println("SERIALIZER);"); - srcWriter.outdent(); - srcWriter.outdent(); - srcWriter.println("}"); - } - - /** - * Generate any fields required by the proxy. - */ - protected void generateProxyFields(SourceWriter srcWriter, - SerializableTypeOracle serializableTypeOracle, - String serializationPolicyStrongName, String remoteServiceInterfaceName) { - // Initialize a field with binary name of the remote service interface - srcWriter.println("private static final String REMOTE_SERVICE_INTERFACE_NAME = " - + "\"" + remoteServiceInterfaceName + "\";"); - srcWriter.println("private static final String SERIALIZATION_POLICY =\"" - + serializationPolicyStrongName + "\";"); - String typeSerializerName = SerializationUtils.getTypeSerializerQualifiedName(serviceIntf); - srcWriter.println("private static final " + typeSerializerName - + " SERIALIZER = new " + typeSerializerName + "();"); - srcWriter.println(); - } - - /** - * Generates the client's asynchronous proxy method. - */ - protected void generateProxyMethod(SourceWriter w, - SerializableTypeOracle serializableTypeOracle, JMethod syncMethod, - JMethod asyncMethod) { - - w.println(); - - // Write the method signature - JType asyncReturnType = asyncMethod.getReturnType().getErasedType(); - w.print("public "); - w.print(asyncReturnType.getQualifiedSourceName()); - w.print(" "); - w.print(asyncMethod.getName() + "("); - - boolean needsComma = false; - NameFactory nameFactory = new NameFactory(); - JParameter[] asyncParams = asyncMethod.getParameters(); - for (int i = 0; i < asyncParams.length; ++i) { - JParameter param = asyncParams[i]; - - if (needsComma) { - w.print(", "); - } else { - needsComma = true; - } - - /* - * Ignoring the AsyncCallback parameter, if any method requires a call to - * SerializationStreamWriter.writeObject we need a try catch block - */ - JType paramType = param.getType(); - paramType = paramType.getErasedType(); - - w.print(paramType.getQualifiedSourceName()); - w.print(" "); - - String paramName = param.getName(); - nameFactory.addName(paramName); - w.print(paramName); - } - - w.println(") {"); - w.indent(); - - String requestIdName = nameFactory.createName("requestId"); - w.println("int " + requestIdName + " = getNextRequestId();"); - - String statsMethodExpr = getProxySimpleName() + "." + syncMethod.getName(); - String tossName = nameFactory.createName("toss"); - w.println("boolean " + tossName + " = isStatsAvailable() && stats(" - + "timeStat(\"" + statsMethodExpr + "\", " + requestIdName - + ", \"begin\"));"); - - w.print(SerializationStreamWriter.class.getSimpleName()); - w.print(" "); - String streamWriterName = nameFactory.createName("streamWriter"); - w.println(streamWriterName + " = createStreamWriter();"); - w.println("// createStreamWriter() prepared the stream"); - w.println("try {"); - w.indent(); - - w.println(streamWriterName + ".writeString(REMOTE_SERVICE_INTERFACE_NAME);"); - - // Write the method name - w.println(streamWriterName + ".writeString(\"" + syncMethod.getName() - + "\");"); - - // Write the parameter count followed by the parameter values - JParameter[] syncParams = syncMethod.getParameters(); - w.println(streamWriterName + ".writeInt(" + syncParams.length + ");"); - for (JParameter param : syncParams) { - JType paramType = param.getType().getErasedType(); - String typeNameExpression = computeTypeNameExpression(paramType); - assert typeNameExpression != null : "Could not compute a type name for " - + paramType.getQualifiedSourceName(); - w.println(streamWriterName + ".writeString(" + typeNameExpression + ");"); - } - - // Encode all of the arguments to the asynchronous method, but exclude the - // last argument which is the callback instance. - // - for (int i = 0; i < asyncParams.length - 1; ++i) { - JParameter asyncParam = asyncParams[i]; - w.print(streamWriterName + "."); - w.print(Shared.getStreamWriteMethodNameFor(asyncParam.getType())); - w.println("(" + asyncParam.getName() + ");"); - } - - String payloadName = nameFactory.createName("payload"); - w.println("String " + payloadName + " = " + streamWriterName - + ".toString();"); - - w.println(tossName + " = isStatsAvailable() && stats(" + "timeStat(\"" - + statsMethodExpr + "\", " + requestIdName - + ", \"requestSerialized\"));"); - - /* - * Depending on the return type for the async method, return a - * RequestBuilder, a Request, or nothing at all. - */ - if (asyncReturnType == JPrimitiveType.VOID) { - w.print("doInvoke("); - } else if (asyncReturnType.getQualifiedSourceName().equals( - RequestBuilder.class.getName())) { - w.print("return doPrepareRequestBuilder("); - } else if (asyncReturnType.getQualifiedSourceName().equals( - Request.class.getName())) { - w.print("return doInvoke("); - } else { - // This method should have been caught by RemoteServiceAsyncValidator - throw new RuntimeException("Unhandled return type " - + asyncReturnType.getQualifiedSourceName()); - } - - JParameter callbackParam = asyncParams[asyncParams.length - 1]; - String callbackName = callbackParam.getName(); - JType returnType = syncMethod.getReturnType(); - w.print("ResponseReader." + getResponseReaderFor(returnType).name()); - w.println(", \"" + getProxySimpleName() + "." + syncMethod.getName() - + "\", " + requestIdName + ", " + payloadName + ", " + callbackName - + ");"); - - w.outdent(); - w.print("} catch (SerializationException "); - String exceptionName = nameFactory.createName("ex"); - w.println(exceptionName + ") {"); - w.indent(); - if (!asyncReturnType.getQualifiedSourceName().equals( - RequestBuilder.class.getName())) { - /* - * If the method returns void or Request, signal the serialization error - * immediately. If the method returns RequestBuilder, the error will be - * signaled whenever RequestBuilder.send() is invoked. - */ - w.println(callbackName + ".onFailure(" + exceptionName + ");"); - } - if (asyncReturnType.getQualifiedSourceName().equals( - RequestBuilder.class.getName())) { - w.println("return new " + FailingRequestBuilder.class.getName() + "(" - + exceptionName + ", " + callbackName + ");"); - } else if (asyncReturnType.getQualifiedSourceName().equals( - Request.class.getName())) { - w.println("return new " + FailedRequest.class.getName() + "();"); - } else { - assert asyncReturnType == JPrimitiveType.VOID; - } - w.outdent(); - w.println("}"); - - w.outdent(); - w.println("}"); - } - - protected void generateProxyMethods(SourceWriter w, - SerializableTypeOracle serializableTypeOracle, - Map syncMethToAsyncMethMap) { - JMethod[] syncMethods = serviceIntf.getOverridableMethods(); - for (JMethod syncMethod : syncMethods) { - - JMethod asyncMethod = syncMethToAsyncMethMap.get(syncMethod); - assert (asyncMethod != null); - - JClassType enclosingType = syncMethod.getEnclosingType(); - JParameterizedType isParameterizedType = enclosingType.isParameterized(); - if (isParameterizedType != null) { - JMethod[] methods = isParameterizedType.getMethods(); - for (int i = 0; i < methods.length; ++i) { - if (methods[i] == syncMethod) { - /* - * Use the generic version of the method to ensure that the server - * can find the method using the erasure of the generic signature. - */ - syncMethod = isParameterizedType.getBaseType().getMethods()[i]; - } - } - } - - generateProxyMethod(w, serializableTypeOracle, syncMethod, asyncMethod); - } - } - - protected void generateStreamWriterOverride(SourceWriter srcWriter) { - srcWriter.println("@Override"); - srcWriter.println("public SerializationStreamWriter createStreamWriter() {"); - srcWriter.indent(); - /* - * Need an explicit cast since we've widened the declaration of the method - * in RemoteServiceProxy. - */ - srcWriter.println("ClientSerializationStreamWriter toReturn ="); - srcWriter.indentln("(ClientSerializationStreamWriter) super.createStreamWriter();"); - srcWriter.println("toReturn.addFlags(ClientSerializationStreamWriter.FLAG_ELIDE_TYPE_NAMES);"); - srcWriter.println("return toReturn;"); - srcWriter.outdent(); - srcWriter.println("}"); - } - - protected void generateTypeHandlers(TreeLogger logger, - GeneratorContext context, SerializableTypeOracle typesSentFromBrowser, - SerializableTypeOracle typesSentToBrowser) - throws UnableToCompleteException { - TypeSerializerCreator tsc = new TypeSerializerCreator(logger, - typesSentFromBrowser, typesSentToBrowser, context, - SerializationUtils.getTypeSerializerQualifiedName(serviceIntf)); - tsc.realize(logger); - - typeStrings = new HashMap(tsc.getTypeStrings()); - typeStrings.put(serviceIntf, TypeNameObfuscator.SERVICE_INTERFACE_ID); - } - - protected String getProxySimpleName() { - String[] name = Shared.synthesizeTopLevelClassName(serviceIntf, - PROXY_SUFFIX); - return name[1]; - } - - protected Class getProxySupertype() { - return RemoteServiceProxy.class; - } - - protected String getRemoteServiceRelativePath() { - RemoteServiceRelativePath moduleRelativeURL = serviceIntf.getAnnotation(RemoteServiceRelativePath.class); - if (moduleRelativeURL != null) { - return "\"" + moduleRelativeURL.value() + "\""; - } - - return null; - } - - protected Class getStreamWriterClass() { - return ClientSerializationStreamWriter.class; - } - - protected String writeSerializationPolicyFile(TreeLogger logger, - GeneratorContext ctx, SerializableTypeOracle serializationSto, - SerializableTypeOracle deserializationSto) - throws UnableToCompleteException { - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - OutputStreamWriter osw = new OutputStreamWriter(baos, - SerializationPolicyLoader.SERIALIZATION_POLICY_FILE_ENCODING); - TypeOracle oracle = ctx.getTypeOracle(); - PrintWriter pw = new PrintWriter(osw); - - JType[] serializableTypes = unionOfTypeArrays( - serializationSto.getSerializableTypes(), - deserializationSto.getSerializableTypes(), new JType[] {serviceIntf}); - - for (int i = 0; i < serializableTypes.length; ++i) { - JType type = serializableTypes[i]; - String binaryTypeName = type.getQualifiedBinaryName(); - pw.print(binaryTypeName); - pw.print(", " - + Boolean.toString(deserializationSto.isSerializable(type))); - pw.print(", " - + Boolean.toString(deserializationSto.maybeInstantiated(type))); - pw.print(", " + Boolean.toString(serializationSto.isSerializable(type))); - pw.print(", " - + Boolean.toString(serializationSto.maybeInstantiated(type))); - pw.print(", " + typeStrings.get(type)); - - /* - * Include the serialization signature to bump the RPC file name if - * obfuscated identifiers are used. - */ - pw.print(", " - + SerializationUtils.getSerializationSignature(oracle, type)); - pw.print('\n'); - - /* - * Emit client-side field information for classes that may be enhanced - * on the server. Each line consists of a comma-separated list - * containing the keyword '@ClientFields', the class name, and a list of - * all potentially serializable client-visible fields. - */ - if ((type instanceof JClassType) - && ((JClassType) type).isEnhanced()) { - JField[] fields = ((JClassType) type).getFields(); - JField[] rpcFields = new JField[fields.length]; - int numRpcFields = 0; - for (JField f : fields) { - if (f.isTransient() || f.isStatic() || f.isFinal()) { - continue; - } - rpcFields[numRpcFields++] = f; - } - - pw.print(SerializationPolicyLoader.CLIENT_FIELDS_KEYWORD); - pw.print(','); - pw.print(binaryTypeName); - for (int idx = 0; idx < numRpcFields; idx++) { - pw.print(','); - pw.print(rpcFields[idx].getName()); - } - pw.print('\n'); - } - } - - // Closes the wrapped streams. - pw.close(); - - byte[] serializationPolicyFileContents = baos.toByteArray(); - String serializationPolicyName = Util.computeStrongName(serializationPolicyFileContents); - - String serializationPolicyFileName = SerializationPolicyLoader.getSerializationPolicyFileName(serializationPolicyName); - OutputStream os = ctx.tryCreateResource(logger, - serializationPolicyFileName); - if (os != null) { - os.write(serializationPolicyFileContents); - GeneratedResource resource = ctx.commitResource(logger, os); - - /* - * Record which proxy class created the resource. A manifest will be - * emitted by the RpcPolicyManifestLinker. - */ - ctx.commitArtifact(logger, new RpcPolicyFileArtifact( - serviceIntf.getQualifiedSourceName(), resource)); - } else { - logger.log(TreeLogger.TRACE, - "SerializationPolicy file for RemoteService '" - + serviceIntf.getQualifiedSourceName() - + "' already exists; no need to rewrite it.", null); - } - - return serializationPolicyName; - } catch (UnsupportedEncodingException e) { - logger.log(TreeLogger.ERROR, - SerializationPolicyLoader.SERIALIZATION_POLICY_FILE_ENCODING - + " is not supported", e); - throw new UnableToCompleteException(); - } catch (IOException e) { - logger.log(TreeLogger.ERROR, null, e); - throw new UnableToCompleteException(); - } - } - - private String getProxyQualifiedName() { - String[] name = Shared.synthesizeTopLevelClassName(serviceIntf, - PROXY_SUFFIX); - return name[0].length() == 0 ? name[1] : name[0] + "." + name[1]; - } - - private ResponseReader getResponseReaderFor(JType returnType) { - if (returnType.isPrimitive() != null) { - return JPRIMITIVETYPE_TO_RESPONSEREADER.get(returnType.isPrimitive()); - } - - if (returnType.getQualifiedSourceName().equals( - String.class.getCanonicalName())) { - return ResponseReader.STRING; - } - - return ResponseReader.OBJECT; - } - - private SourceWriter getSourceWriter(TreeLogger logger, GeneratorContext ctx, - JClassType serviceAsync) { - JPackage serviceIntfPkg = serviceAsync.getPackage(); - String packageName = serviceIntfPkg == null ? "" : serviceIntfPkg.getName(); - PrintWriter printWriter = ctx.tryCreate(logger, packageName, - getProxySimpleName()); - if (printWriter == null) { - return null; - } - - ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory( - packageName, getProxySimpleName()); - - String[] imports = new String[] { - getProxySupertype().getCanonicalName(), - getStreamWriterClass().getCanonicalName(), - SerializationStreamWriter.class.getCanonicalName(), - GWT.class.getCanonicalName(), ResponseReader.class.getCanonicalName(), - SerializationException.class.getCanonicalName(), - Impl.class.getCanonicalName()}; - for (String imp : imports) { - composerFactory.addImport(imp); - } - - composerFactory.setSuperclass(getProxySupertype().getSimpleName()); - composerFactory.addImplementedInterface(serviceAsync.getErasedType().getQualifiedSourceName()); - - return composerFactory.createSourceWriter(ctx, printWriter); - } -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/RemoteServiceAsyncValidator.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/RemoteServiceAsyncValidator.java deleted file mode 100755 index 7a0073dc545..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/RemoteServiceAsyncValidator.java +++ /dev/null @@ -1,245 +0,0 @@ -/* - * Copyright 2007 Google Inc. - * - * 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 de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc; - -import com.google.gwt.core.ext.TreeLogger; -import com.google.gwt.core.ext.UnableToCompleteException; -import com.google.gwt.core.ext.typeinfo.JClassType; -import com.google.gwt.core.ext.typeinfo.JMethod; -import com.google.gwt.core.ext.typeinfo.JPackage; -import com.google.gwt.core.ext.typeinfo.JParameter; -import com.google.gwt.core.ext.typeinfo.JPrimitiveType; -import com.google.gwt.core.ext.typeinfo.JType; -import com.google.gwt.core.ext.typeinfo.NotFoundException; -import com.google.gwt.core.ext.typeinfo.TypeOracle; -import com.google.gwt.http.client.Request; -import com.google.gwt.http.client.RequestBuilder; -import com.google.gwt.user.client.rpc.AsyncCallback; - -import java.util.HashMap; -import java.util.Map; -import java.util.TreeMap; - -/** - * Validates the asynchronous version of - * {@link com.google.gwt.user.client.rpc.RemoteService RemoteService} interface. - */ -class RemoteServiceAsyncValidator { - static void logValidAsyncInterfaceDeclaration(TreeLogger logger, - JClassType remoteService) { - TreeLogger branch = logger.branch(TreeLogger.INFO, - "A valid definition for the asynchronous version of interface '" - + remoteService.getQualifiedSourceName() + "' would be:\n", null); - branch.log(TreeLogger.ERROR, - synthesizeAsynchronousInterfaceDefinition(remoteService), null); - } - - private static String computeAsyncMethodSignature(JMethod syncMethod, - JClassType asyncCallbackClass) { - return computeInternalSignature(syncMethod) + "/" - + asyncCallbackClass.getQualifiedSourceName(); - } - - private static String computeInternalSignature(JMethod method) { - StringBuffer sb = new StringBuffer(); - sb.setLength(0); - sb.append(method.getName()); - JParameter[] params = method.getParameters(); - for (JParameter param : params) { - sb.append("/"); - JType paramType = param.getType(); - sb.append(paramType.getErasedType().getQualifiedSourceName()); - } - return sb.toString(); - } - - /** - * Builds a map of asynchronous method internal signatures to the - * corresponding asynchronous {@link JMethod}. - */ - private static Map initializeAsyncMethodMap( - JMethod[] asyncMethods) { - Map sigs = new TreeMap(); - for (JMethod asyncMethod : asyncMethods) { - sigs.put(computeInternalSignature(asyncMethod), asyncMethod); - } - return sigs; - } - - private static String synthesizeAsynchronousInterfaceDefinition( - JClassType serviceIntf) { - StringBuffer sb = new StringBuffer(); - JPackage pkg = serviceIntf.getPackage(); - if (pkg != null) { - sb.append("\npackage "); - sb.append(pkg.getName()); - sb.append(";\n"); - } - - sb.append("\npublic interface "); - sb.append(serviceIntf.getSimpleSourceName()); - sb.append("Async {\n"); - - JMethod[] methods = serviceIntf.getOverridableMethods(); - for (JMethod method : methods) { - assert (method != null); - - sb.append("\tvoid "); - sb.append(method.getName()); - sb.append("("); - - JParameter[] params = method.getParameters(); - for (int paramIndex = 0; paramIndex < params.length; ++paramIndex) { - JParameter param = params[paramIndex]; - - if (paramIndex > 0) { - sb.append(", "); - } - - sb.append(param.toString()); - } - - if (params.length > 0) { - sb.append(", "); - } - - JType returnType = method.getReturnType(); - sb.append(AsyncCallback.class.getName()); - sb.append("<"); - if (returnType instanceof JPrimitiveType) { - sb.append(((JPrimitiveType) returnType).getQualifiedBoxedSourceName()); - } else { - sb.append(returnType.getParameterizedQualifiedSourceName()); - } - sb.append("> arg"); - sb.append(Integer.toString(params.length + 1)); - sb.append(");\n"); - } - - sb.append("}"); - - return sb.toString(); - } - - private static void validationFailed(TreeLogger branch, - JClassType remoteService) throws UnableToCompleteException { - logValidAsyncInterfaceDeclaration(branch, remoteService); - throw new UnableToCompleteException(); - } - - /** - * {@link JClassType} for the {@link AsyncCallback} interface. - */ - private final JClassType asyncCallbackClass; - - /** - * {@link JClassType} for the {@link RequestBuilder} class. - */ - private final JClassType requestBuilderType; - - /** - * {@link JClassType} for the {@link Request} class. - */ - private final JClassType requestType; - - RemoteServiceAsyncValidator(TreeLogger logger, TypeOracle typeOracle) - throws UnableToCompleteException { - try { - asyncCallbackClass = typeOracle.getType(AsyncCallback.class.getName()); - requestType = typeOracle.getType(Request.class.getCanonicalName()); - requestBuilderType = typeOracle.getType(RequestBuilder.class.getCanonicalName()); - } catch (NotFoundException e) { - logger.log(TreeLogger.ERROR, null, e); - throw new UnableToCompleteException(); - } - } - - /** - * Checks that for every method on the synchronous remote service interface - * there is a corresponding asynchronous version in the asynchronous version - * of the remote service. If the validation succeeds, a map of synchronous to - * asynchronous methods is returned. - * - * @param logger - * @param remoteService - * @return map of synchronous method to asynchronous method - * - * @throws UnableToCompleteException if the asynchronous - * {@link com.google.gwt.user.client.rpc.RemoteService RemoteService} - * was not found, or if it does not have an asynchronous method - * version of every synchronous one - */ - public Map validate(TreeLogger logger, - JClassType remoteService, JClassType remoteServiceAsync) - throws UnableToCompleteException { - TreeLogger branch = logger.branch(TreeLogger.DEBUG, - "Checking the synchronous interface '" - + remoteService.getQualifiedSourceName() - + "' against its asynchronous version '" - + remoteServiceAsync.getQualifiedSourceName() + "'", null); - - // Sync and async versions must have the same number of methods - JMethod[] asyncMethods = remoteServiceAsync.getOverridableMethods(); - JMethod[] syncMethods = remoteService.getOverridableMethods(); - if (asyncMethods.length != syncMethods.length) { - branch.branch(TreeLogger.ERROR, "The asynchronous version of " - + remoteService.getQualifiedSourceName() + " has " - + (asyncMethods.length > syncMethods.length ? "more" : "less") - + " methods than the synchronous version", null); - validationFailed(branch, remoteService); - } - - // Check that for every sync method there is a corresponding async method - boolean failed = false; - Map asyncMethodMap = initializeAsyncMethodMap(asyncMethods); - Map syncMethodToAsyncMethodMap = new HashMap(); - for (JMethod syncMethod : syncMethods) { - String asyncSig = computeAsyncMethodSignature(syncMethod, - asyncCallbackClass); - JMethod asyncMethod = asyncMethodMap.get(asyncSig); - if (asyncMethod == null) { - branch.branch(TreeLogger.ERROR, - "Missing asynchronous version of the synchronous method '" - + syncMethod.getReadableDeclaration() + "'", null); - failed = true; - } else { - // TODO if async param is parameterized make sure that the sync return - // type is assignable to the first type argument - JType returnType = asyncMethod.getReturnType(); - if (returnType != JPrimitiveType.VOID && returnType != requestType - && returnType != requestBuilderType) { - branch.branch(TreeLogger.ERROR, - "The asynchronous version of the synchronous method '" - + syncMethod.getReadableDeclaration() - + "' must have a return type of 'void' or '" - + Request.class.getCanonicalName() + "' or '" - + RequestBuilder.class.getCanonicalName() + "'", null); - failed = true; - } else { - syncMethodToAsyncMethodMap.put(syncMethod, asyncMethod); - } - } - } - - if (failed) { - validationFailed(branch, remoteService); - } - - branch.log(TreeLogger.DEBUG, "Interfaces are in sync"); - - return syncMethodToAsyncMethodMap; - } -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/SerializableTypeOracle.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/SerializableTypeOracle.java deleted file mode 100755 index 4298d43781a..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/SerializableTypeOracle.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2007 Google Inc. - * - * 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 de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc; - -import com.google.gwt.core.ext.typeinfo.JType; - -/** - * Interface implemented by any class that wants to answer questions about - * serializable types for a given - * {@link com.google.gwt.user.client.rpc.RemoteService RemoteService}. - */ -public interface SerializableTypeOracle { - - /** - * Returns the list of all types that are considered serializable. - * - * @return array of serializable types - */ - JType[] getSerializableTypes(); - - /** - * Returns true if the type is serializable. If a type is serializable then - * there is a secondary type called a FieldSerializer that provides the - * behavior necessary to serialize or deserialize the fields of an instance. - * - * @param type the type that maybe serializable - * @return true if the type is serializable - */ - boolean isSerializable(JType type); - - /** - * Returns true if the type might be instantiated as part of - * deserialization or serialization. - * - * @param type the type to test - * @return true if the type might be instantiated - */ - boolean maybeInstantiated(JType type); -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/SerializableTypeOracleBuilder.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/SerializableTypeOracleBuilder.java deleted file mode 100755 index 8ebd0b202a9..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/SerializableTypeOracleBuilder.java +++ /dev/null @@ -1,1655 +0,0 @@ -/* - * Copyright 2008 Google Inc. - * - * 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 de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc; - -import java.io.OutputStream; -import java.io.PrintWriter; -import java.io.Serializable; -import java.lang.annotation.Annotation; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; -import java.util.Map.Entry; - -import com.google.gwt.core.ext.PropertyOracle; -import com.google.gwt.core.ext.TreeLogger; -import com.google.gwt.core.ext.UnableToCompleteException; -import com.google.gwt.core.ext.TreeLogger.Type; -import com.google.gwt.core.ext.typeinfo.JArrayType; -import com.google.gwt.core.ext.typeinfo.JClassType; -import com.google.gwt.core.ext.typeinfo.JField; -import com.google.gwt.core.ext.typeinfo.JGenericType; -import com.google.gwt.core.ext.typeinfo.JParameterizedType; -import com.google.gwt.core.ext.typeinfo.JRealClassType; -import com.google.gwt.core.ext.typeinfo.JType; -import com.google.gwt.core.ext.typeinfo.JTypeParameter; -import com.google.gwt.core.ext.typeinfo.JWildcardType; -import com.google.gwt.core.ext.typeinfo.NotFoundException; -import com.google.gwt.core.ext.typeinfo.TypeOracle; -import com.google.gwt.dev.util.log.PrintWriterTreeLogger; -import com.google.gwt.user.client.rpc.GwtTransient; -import com.google.gwt.user.client.rpc.IsSerializable; - -import de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc.ProblemReport.Priority; -import de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc.TypeParameterExposureComputer.TypeParameterFlowInfo; -import de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc.TypePaths.TypePath; - -/** - * Builds a {@link SerializableTypeOracle} for a given set of root types. - * - *

- * There are two goals for this builder. First, discover the set of serializable - * types that can be serialized if you serialize one of the root types. Second, - * to make sure that all root types can actually be serialized by GWT. - *

- * - *

- * To find the serializable types, it includes the root types, and then it - * iteratively traverses the type hierarchy and the fields of any type already - * deemed serializable. To improve the accuracy of the traversal there is a - * computations of the exposure of type parameters. When the traversal reaches a - * parameterized type, these exposure values are used to determine how to treat - * the arguments. - *

- * - *

- * A type qualifies for serialization if it or one of its subtypes is - * automatically or manually serializable. Automatic serialization is selected - * if the type is assignable to {@link IsSerializable} or {@link Serializable} - * or if the type is a primitive type such as int, boolean, etc. Manual - * serialization is selected if there exists another type with the same fully - * qualified name concatenated with "_CustomFieldSerializer". If a type - * qualifies for both manual and automatic serialization, manual serialization - * is preferred. - *

- * - *

- * Some types may be marked as "enhanced," either automatically by the presence - * of a JDO @PersistenceCapable or JPA @Entity tag on - * the class definition, or manually by extending the 'rpc.enhancedClasses' - * configuration property in the GWT module XML file. For example, to manually - * mark the class com.google.myapp.MyPersistentClass as enhanced, use: - * - *

- * 
- * 
- * - *

- * Enhanced classes are checked for the presence of additional serializable - * fields on the server that were not defined in client code as seen by the GWT - * compiler. If it is possible for an instance of such a class to be transmitted - * bidrectionally between server and client, a special RPC rule is used. The - * server-only fields are serialized using standard Java serialization and sent - * between the client and server as a blob of opaque base-64 encoded binary - * data. When an instance is sent from client to server, the server instance is - * populated by invoking setter methods where possible rather than by setting - * fields directly. This allows APIs such as JDO the opportunity to update the - * object state properly to take into account changes that may have occurred to - * the object's state while resident on the client. - *

- */ -public class SerializableTypeOracleBuilder { - - class TypeInfoComputed { - /** - * All instantiable types found when this type was quaried, including the - * type itself. - */ - private Set instantiableTypes = new HashSet(); - - /** - * true if the type is assignable to {@link IsSerializable} or - * {@link java.io.Serializable Serializable}. - */ - private final boolean autoSerializable; - - /** - * true if the this type directly implements one of the marker - * interfaces. - */ - private final boolean directlyImplementsMarker; - - /** - * true if the type is automatically or manually serializable - * and the corresponding checks succeed. - */ - private boolean fieldSerializable = false; - - /** - * true if this type might be instantiated. - */ - private boolean instantiable = false; - - /** - * true if there are instantiable subtypes assignable to this - * one. - */ - private boolean instantiableSubtypes; - - /** - * Custom field serializer or null if there isn't one. - */ - private final JClassType manualSerializer; - - /** - * true if this class might be enhanced on the server to - * contain extra fields. - */ - private final boolean maybeEnhanced; - - /** - * Path used to discover this type. - */ - private final TypePath path; - - /** - * The state that this type is currently in. - */ - private TypeState state = TypeState.NOT_CHECKED; - - /** - * {@link JClassType} associated with this metadata. - */ - private final JType type; - - public TypeInfoComputed(JType type, TypePath path) { - this.type = type; - this.path = path; - if (type instanceof JClassType) { - JClassType typeClass = (JClassType) type; - autoSerializable = SerializableTypeOracleBuilder.isAutoSerializable(typeClass); - manualSerializer = findCustomFieldSerializer(typeOracle, typeClass); - directlyImplementsMarker = directlyImplementsMarkerInterface(typeClass); - maybeEnhanced = hasJdoAnnotation(typeClass) - || hasJpaAnnotation(typeClass); - } else { - autoSerializable = false; - manualSerializer = null; - directlyImplementsMarker = false; - maybeEnhanced = false; - } - } - - /** - * Returns the internal set of instantiable types for this TIC. - * Modifications to this set are immediately recorded into the TIC as well. - * TODO(spoon) maybe pass the TIC around instead of the set? - * then there could be addInstantiableType(JClassType) instead of - * speccing this to be mutable. - */ - public Set getInstantiableTypes() { - return instantiableTypes; - } - - public JClassType getManualSerializer() { - return manualSerializer; - } - - public TypePath getPath() { - return path; - } - - public JType getType() { - return type; - } - - public boolean hasInstantiableSubtypes() { - return isInstantiable() || instantiableSubtypes - || isPendingInstantiable(); - } - - public boolean isAutoSerializable() { - return autoSerializable; - } - - public boolean isDeclaredSerializable() { - return autoSerializable || isManuallySerializable(); - } - - public boolean isDirectlySerializable() { - return directlyImplementsMarker || isManuallySerializable(); - } - - public boolean isDone() { - return state == TypeState.CHECK_DONE; - } - - public boolean isFieldSerializable() { - return fieldSerializable; - } - - public boolean isInstantiable() { - return instantiable; - } - - public boolean isManuallySerializable() { - return manualSerializer != null; - } - - public boolean isPendingInstantiable() { - return state == TypeState.CHECK_IN_PROGRESS; - } - - public boolean maybeEnhanced() { - return maybeEnhanced; - } - - public void setFieldSerializable() { - fieldSerializable = true; - } - - public void setInstantiable(boolean instantiable) { - this.instantiable = instantiable; - if (instantiable) { - fieldSerializable = true; - } - state = TypeState.CHECK_DONE; - } - - public void setInstantiableSubtypes(boolean instantiableSubtypes) { - this.instantiableSubtypes = instantiableSubtypes; - } - - public void setPendingInstantiable() { - state = TypeState.CHECK_IN_PROGRESS; - } - } - - private enum TypeState { - /** - * The instantiability of a type has been determined. - */ - CHECK_DONE("Check succeeded"), - /** - * The instantiability of a type is being checked. - */ - CHECK_IN_PROGRESS("Check in progress"), - /** - * The instantiability of a type has not been checked. - */ - NOT_CHECKED("Not checked"); - - private final String message; - - TypeState(String message) { - this.message = message; - } - - @Override - public String toString() { - return message; - } - } - - /** - * Compares {@link JType}s according to their qualified source names. - */ - static final Comparator JTYPE_COMPARATOR = new Comparator() { - public int compare(JType t1, JType t2) { - return t1.getQualifiedSourceName().compareTo(t2.getQualifiedSourceName()); - } - }; - - /** - * No type filtering by default.. - */ - private static final TypeFilter DEFAULT_TYPE_FILTER = new TypeFilter() { - public String getName() { - return "Default"; - } - - public boolean isAllowed(JClassType type) { - return true; - } - }; - - /** - * A reference to the annotation class - * javax.jdo.annotations.PersistenceCapable used by the JDO API. May be null - * if JDO is not present in the runtime environment. - */ - private static Class JDO_PERSISTENCE_CAPABLE_ANNOTATION = null; - - /** - * A reference to the method 'String - * javax.jdo.annotations.PersistenceCapable.detachable()'. - */ - private static Method JDO_PERSISTENCE_CAPABLE_DETACHABLE_METHOD; - - /** - * A reference to the annotation class javax.persistence.Entity used by the - * JPA API. May be null if JPA is not present in the runtime environment. - */ - private static Class JPA_ENTITY_ANNOTATION = null; - - static { - try { - JDO_PERSISTENCE_CAPABLE_ANNOTATION = Class.forName( - "javax.jdo.annotations.PersistenceCapable").asSubclass( - Annotation.class); - JDO_PERSISTENCE_CAPABLE_DETACHABLE_METHOD = - JDO_PERSISTENCE_CAPABLE_ANNOTATION.getDeclaredMethod("detachable", (Class[]) null); - } catch (ClassNotFoundException e) { - // Ignore, JDO_PERSISTENCE_CAPABLE_ANNOTATION will be null - } catch (NoSuchMethodException e) { - JDO_PERSISTENCE_CAPABLE_ANNOTATION = null; - } - - try { - JPA_ENTITY_ANNOTATION = Class.forName("javax.persistence.Entity").asSubclass( - Annotation.class); - } catch (ClassNotFoundException e) { - // Ignore, JPA_ENTITY_CAPABLE_ANNOTATION will be null - } - } - - static boolean canBeInstantiated(JClassType type, ProblemReport problems) { - if (type.isEnum() == null) { - if (type.isAbstract()) { - // Abstract types will be picked up if there is an instantiable - // subtype. - return false; - } - - if (!type.isDefaultInstantiable() && !isManuallySerializable(type)) { - // Warn and return false. - problems.add(type, type.getParameterizedQualifiedSourceName() + - " is not default instantiable (it must have a zero-argument " - + "constructor or no constructors at all) and has no custom " - + "serializer.", Priority.DEFAULT); - return false; - } - } else { - /* - * Enums are always instantiable regardless of abstract or default - * instantiability. - */ - } - - return true; - } - - /** - * Finds the custom field serializer for a given type. - * - * @param typeOracle - * @param type - * @return the custom field serializer for a type or null if - * there is not one - */ - public static JClassType findCustomFieldSerializer(TypeOracle typeOracle, JType type) { - JClassType classOrInterface = type.isClassOrInterface(); - if (classOrInterface == null) { - return null; - } - - String customFieldSerializerName = type.getQualifiedSourceName() - + "_CustomFieldSerializer"; - JClassType customSerializer = typeOracle.findType(customFieldSerializerName); - if (customSerializer == null) { - // If the type is in the java.lang or java.util packages then it will be - // mapped into com.google.gwt.user.client.rpc.core package - customSerializer = typeOracle.findType("com.google.gwt.user.client.rpc.core." - + customFieldSerializerName); - } - - return customSerializer; - } - - static JRealClassType getBaseType(JClassType type) { - if (type.isParameterized() != null) { - return type.isParameterized().getBaseType(); - } else if (type.isRawType() != null) { - return type.isRawType().getBaseType(); - } - - return (JRealClassType) type; - } - - /** - * @param type the type to query - * @return true if the type is annotated with @PersistenceCapable(..., - * detachable="true") - */ - static boolean hasJdoAnnotation(JClassType type) { - if (JDO_PERSISTENCE_CAPABLE_ANNOTATION == null) { - return false; - } - Annotation annotation = type.getAnnotation(JDO_PERSISTENCE_CAPABLE_ANNOTATION); - if (annotation == null) { - return false; - } - try { - Object value = JDO_PERSISTENCE_CAPABLE_DETACHABLE_METHOD.invoke( - annotation, (Object[]) null); - if (value instanceof String) { - return "true".equalsIgnoreCase((String) value); - } else { - return false; - } - } catch (IllegalAccessException e) { - // will return false - } catch (InvocationTargetException e) { - // will return false - } - - return false; - } - - /** - * @param type the type to query - * @return true if the type is annotated with @Entity - */ - static boolean hasJpaAnnotation(JClassType type) { - if (JPA_ENTITY_ANNOTATION == null) { - return false; - } - Annotation annotation = type.getAnnotation(JPA_ENTITY_ANNOTATION); - return annotation != null; - } - - static boolean isAutoSerializable(JClassType type) { - try { - JClassType isSerializable = getIsSerializableMarkerInterface(type); - JClassType serializable = getSerializableMarkerInterface(type); - return type.isAssignableTo(isSerializable) - || type.isAssignableTo(serializable); - } catch (NotFoundException e) { - return false; - } - } - - /** - * Returns true if this type is part of the standard java - * packages. - */ - static boolean isInStandardJavaPackage(String className) { - if (className.startsWith("java.")) { - return true; - } - - if (className.startsWith("javax.")) { - return true; - } - - return false; - } - - static void recordTypeParametersIn(JType type, Set params) { - JTypeParameter isTypeParameter = type.isTypeParameter(); - if (isTypeParameter != null) { - params.add(isTypeParameter); - } - - JArrayType isArray = type.isArray(); - if (isArray != null) { - recordTypeParametersIn(isArray.getComponentType(), params); - } - - JWildcardType isWildcard = type.isWildcard(); - if (isWildcard != null) { - for (JClassType bound : isWildcard.getUpperBounds()) { - recordTypeParametersIn(bound, params); - } - } - - JParameterizedType isParameterized = type.isParameterized(); - if (isParameterized != null) { - for (JClassType arg : isParameterized.getTypeArgs()) { - recordTypeParametersIn(arg, params); - } - } - } - - /** - * Return true if a class's fields should be considered for - * serialization. If it returns false then none of the fields of - * this class should be serialized. - */ - static boolean shouldConsiderFieldsForSerialization(JClassType type, - TypeFilter filter, ProblemReport problems) { - if (!isAllowedByFilter(filter, type, problems)) { - return false; - } - - if (!isDeclaredSerializable(type)) { - problems.add(type, type.getParameterizedQualifiedSourceName() - + " is not assignable to '" + IsSerializable.class.getName() - + "' or '" + Serializable.class.getName() - + "' nor does it have a custom field serializer", Priority.DEFAULT); - return false; - } - - if (isManuallySerializable(type)) { - JClassType manualSerializer = findCustomFieldSerializer(type.getOracle(), - type); - assert (manualSerializer != null); - - List fieldProblems = CustomFieldSerializerValidator.validate( - manualSerializer, type); - if (!fieldProblems.isEmpty()) { - for (String problem : fieldProblems) { - problems.add(type, problem, Priority.FATAL); - } - return false; - } - } else { - assert (isAutoSerializable(type)); - - if (!isAccessibleToSerializer(type)) { - // Class is not visible to a serializer class in the same package - problems.add(type, type.getParameterizedQualifiedSourceName() - + " is not accessible from a class in its same package; it " - + "will be excluded from the set of serializable types", - Priority.DEFAULT); - return false; - } - - if (type.isMemberType() && !type.isStatic()) { - // Non-static member types cannot be serialized - problems.add(type, - type.getParameterizedQualifiedSourceName() + " is nested but " + - "not static; it will be excluded from the set of serializable " + - "types", Priority.DEFAULT); - return false; - } - } - - return true; - } - - /** - * Returns true if the field qualifies for serialization without - * considering its type. - */ - static boolean shouldConsiderForSerialization(TreeLogger logger, - boolean suppressNonStaticFinalFieldWarnings, JField field) { - if (field.isStatic() || field.isTransient()) { - return false; - } - - if (field.isAnnotationPresent(GwtTransient.class)) { - return false; - } - - if (field.isFinal()) { - Type logLevel; - if (isManuallySerializable(field.getEnclosingType())) { - /* - * If the type has a custom serializer, assume the programmer knows - * best. - */ - logLevel = TreeLogger.DEBUG; - } else { - logLevel = TreeLogger.WARN; - } - logger.branch(suppressNonStaticFinalFieldWarnings ? TreeLogger.DEBUG - : logLevel, "Field '" + field.toString() - + "' will not be serialized because it is final", null); - return false; - } - - return true; - } - - private static boolean directlyImplementsMarkerInterface(JClassType type) { - try { - return TypeHierarchyUtils.directlyImplementsInterface(type, - getIsSerializableMarkerInterface(type)) - || TypeHierarchyUtils.directlyImplementsInterface(type, - getSerializableMarkerInterface(type)); - } catch (NotFoundException e) { - return false; - } - } - - private static JArrayType getArrayType(TypeOracle typeOracle, int rank, - JType component) { - assert (rank > 0); - - JArrayType array = null; - JType currentComponent = component; - for (int i = 0; i < rank; ++i) { - array = typeOracle.getArrayType(currentComponent); - currentComponent = array; - } - - return array; - } - - private static JClassType getIsSerializableMarkerInterface(JClassType type) - throws NotFoundException { - return type.getOracle().getType(IsSerializable.class.getName()); - } - - private static JClassType getSerializableMarkerInterface(JClassType type) - throws NotFoundException { - return type.getOracle().getType(Serializable.class.getName()); - } - - /** - * Returns true if a serializer class could access this type. - */ - private static boolean isAccessibleToSerializer(JClassType type) { - if (type.isPrivate()) { - return false; - } - - if (isInStandardJavaPackage(type.getQualifiedSourceName())) { - if (!type.isPublic()) { - return false; - } - } - - if (type.isMemberType()) { - return isAccessibleToSerializer(type.getEnclosingType()); - } - - return true; - } - - private static boolean isAllowedByFilter(TypeFilter filter, - JClassType classType, ProblemReport problems) { - if (!filter.isAllowed(classType)) { - problems.add(classType, - classType.getParameterizedQualifiedSourceName() - + " is excluded by type filter ", Priority.AUXILIARY); - return false; - } - - return true; - } - - private static boolean isDeclaredSerializable(JClassType type) { - return isAutoSerializable(type) || isManuallySerializable(type); - } - - private static boolean isDirectlySerializable(JClassType type) { - return directlyImplementsMarkerInterface(type) - || isManuallySerializable(type); - } - - private static boolean isManuallySerializable(JClassType type) { - return findCustomFieldSerializer(type.getOracle(), type) != null; - } - - private static void logSerializableTypes(TreeLogger logger, - Set fieldSerializableTypes) { - TreeLogger localLogger = logger.branch(TreeLogger.DEBUG, "Identified " - + fieldSerializableTypes.size() + " serializable type" - + ((fieldSerializableTypes.size() == 1) ? "" : "s"), null); - - for (JClassType fieldSerializableType : fieldSerializableTypes) { - localLogger.branch(TreeLogger.DEBUG, - fieldSerializableType.getParameterizedQualifiedSourceName(), null); - } - } - - private boolean alreadyCheckedObject; - - /** - * Cache of the {@link JClassType} for {@link Collection}. - */ - private final JGenericType collectionClass; - - private Set enhancedClasses = null; - - private OutputStream logOutputStream; - - /** - * Cache of the {@link JClassType} for {@link Map}. - */ - private final JGenericType mapClass; - - private final Map rootTypes = new LinkedHashMap(); - - /** - * If true we will not warn if a serializable type contains a - * non-static final field. We warn because these fields are not serialized. - */ - private final boolean suppressNonStaticFinalFieldWarnings; - - private final TypeConstrainer typeConstrainer; - private TypeFilter typeFilter = DEFAULT_TYPE_FILTER; - - private final TypeOracle typeOracle; - - private final TypeParameterExposureComputer typeParameterExposureComputer = new TypeParameterExposureComputer( - typeFilter); - - /** - * The set of type parameters that appear in one of the root types. - * TODO(spoon): It would be cleaner to delete this field, and instead to have - * {@link #addRootType(TreeLogger, JType)} replace parameters with wildcard - * types. Then the root types would not contain any parameters. - */ - private Set typeParametersInRootTypes = new HashSet(); - - /** - * Map of {@link JType} to {@link TypeInfoComputed}. - */ - private final Map typeToTypeInfoComputed = new HashMap(); - - /** - * Constructs a builder. - * - * @param logger - * @param propertyOracle - * @param typeOracle - * - * @throws UnableToCompleteException if we fail to find one of our special - * types - */ - public SerializableTypeOracleBuilder(TreeLogger logger, - PropertyOracle propertyOracle, TypeOracle typeOracle) - throws UnableToCompleteException { - this.typeOracle = typeOracle; - typeConstrainer = new TypeConstrainer(typeOracle); - - try { - collectionClass = typeOracle.getType(Collection.class.getName()).isGenericType(); - mapClass = typeOracle.getType(Map.class.getName()).isGenericType(); - } catch (NotFoundException e) { - logger.log(TreeLogger.ERROR, null, e); - throw new UnableToCompleteException(); - } - - suppressNonStaticFinalFieldWarnings = Shared.shouldSuppressNonStaticFinalFieldWarnings( - logger, propertyOracle); - enhancedClasses = Shared.getEnhancedTypes(propertyOracle); - } - - public void addRootType(TreeLogger logger, JType type) { - if (type.isPrimitive() != null) { - return; - } - - JClassType clazz = (JClassType) type; - if (!rootTypes.containsKey(clazz)) { - recordTypeParametersIn(type, typeParametersInRootTypes); - - rootTypes.put(clazz, logger); - } else { - logger.log(TreeLogger.TRACE, clazz.getParameterizedQualifiedSourceName() - + " is already a root type."); - } - } - - /** - * Builds a {@link SerializableTypeOracle} for a given set of root types. - * - * @param logger - * - * @return a {@link SerializableTypeOracle} for the specified set of root - * types - * - * @throws UnableToCompleteException if there was not at least one - * instantiable type assignable to each of the specified root types - */ - public SerializableTypeOracle build(TreeLogger logger) - throws UnableToCompleteException { - alreadyCheckedObject = false; - - boolean allSucceeded = true; - - for (Entry entry : rootTypes.entrySet()) { - ProblemReport problems = new ProblemReport(); - problems.setContextType(entry.getKey()); - boolean entrySucceeded = computeTypeInstantiability(entry.getValue(), - entry.getKey(), TypePaths.createRootPath(entry.getKey()), problems).hasInstantiableSubtypes(); - if (!entrySucceeded) { - problems.report(logger, TreeLogger.ERROR, TreeLogger.INFO); - } else { - if (problems.hasFatalProblems()) { - entrySucceeded = false; - problems.reportFatalProblems(logger, TreeLogger.ERROR); - } - // if entrySucceeded, there may still be "warning" problems, but too - // often they're expected (e.g. non-instantiable subtypes of List), so - // we log them at DEBUG. - // TODO(fabbott): we could blacklist or graylist those types here, so - // instantiation during code generation would flag them for us. - problems.report(logger, TreeLogger.DEBUG, TreeLogger.DEBUG); - } - - allSucceeded &= entrySucceeded; - } - - if (!allSucceeded) { - throw new UnableToCompleteException(); - } - - for (TypeInfoComputed tic : typeToTypeInfoComputed.values()) { - assert (!tic.isPendingInstantiable()); - } - - pruneUnreachableTypes(); - - logReachableTypes(logger); - - Set possiblyInstantiatedTypes = new TreeSet( - JTYPE_COMPARATOR); - - Set fieldSerializableTypes = new TreeSet( - JTYPE_COMPARATOR); - - for (TypeInfoComputed tic : typeToTypeInfoComputed.values()) { - if (!(tic.getType() instanceof JClassType)) { - continue; - } - JClassType type = (JClassType) tic.getType(); - - type = type.getErasedType(); - - if (tic.isInstantiable()) { - assert (!type.isAbstract() || type.isEnum() != null); - - possiblyInstantiatedTypes.add(type); - } - - if (tic.isFieldSerializable()) { - assert (type.isInterface() == null); - - fieldSerializableTypes.add(type); - } - - if (tic.maybeEnhanced() - || (enhancedClasses != null - && enhancedClasses.contains(type.getQualifiedSourceName()))) { - type.setEnhanced(); - } - } - - logSerializableTypes(logger, fieldSerializableTypes); - - return new SerializableTypeOracleImpl(fieldSerializableTypes, - possiblyInstantiatedTypes); - } - - /** - * Set the {@link OutputStream} which will receive a detailed log of the types - * which were examined in order to determine serializability. - */ - public void setLogOutputStream(OutputStream logOutputStream) { - this.logOutputStream = logOutputStream; - } - - public void setTypeFilter(TypeFilter typeFilter) { - this.typeFilter = typeFilter; - typeParameterExposureComputer.setTypeFilter(typeFilter); - } - - /** - * This method determines information about serializing a type with GWT. To do - * so, it must traverse all subtypes as well as all field types of those - * types, transitively. - * - * It returns a {@link TypeInfoComputed} with the information found. - * - * As a side effect, all types needed--plus some--to serialize this type are - * accumulated in {@link #typeToTypeInfoComputed}. In particular, there will - * be an entry for any type that has been validated by this method, as a - * shortcircuit to avoid recomputation. - * - * The method is exposed using default access to enable testing. - */ - TypeInfoComputed computeTypeInstantiability(TreeLogger logger, JType type, - TypePath path, ProblemReport problems) { - assert (type != null); - if (type.isPrimitive() != null) { - TypeInfoComputed tic = getTypeInfoComputed(type, path, true); - tic.setInstantiableSubtypes(true); - tic.setInstantiable(false); - return tic; - } - - assert (type instanceof JClassType); - - JClassType classType = (JClassType) type; - - TypeInfoComputed tic = getTypeInfoComputed(classType, path, false); - if (tic != null && tic.isDone()) { - // we have an answer already; use it. - return tic; - } - - TreeLogger localLogger = logger.branch(TreeLogger.DEBUG, - classType.getParameterizedQualifiedSourceName(), null); - - JTypeParameter isTypeParameter = classType.isTypeParameter(); - if (isTypeParameter != null) { - if (typeParametersInRootTypes.contains(isTypeParameter)) { - return computeTypeInstantiability(localLogger, - isTypeParameter.getFirstBound(), - TypePaths.createTypeParameterInRootPath(path, isTypeParameter), - problems); - } - - /* - * This type parameter was not in a root type and therefore it is the - * caller's responsibility to deal with it. We assume that it is - * indirectly instantiable here. - */ - tic = getTypeInfoComputed(classType, path, true); - tic.setInstantiableSubtypes(true); - tic.setInstantiable(false); - return tic; - } - - JWildcardType isWildcard = classType.isWildcard(); - if (isWildcard != null) { - boolean success = true; - for (JClassType bound : isWildcard.getUpperBounds()) { - success &= computeTypeInstantiability(localLogger, bound, path, problems).hasInstantiableSubtypes(); - } - tic = getTypeInfoComputed(classType, path, true); - tic.setInstantiableSubtypes(success); - tic.setInstantiable(false); - return tic; - } - - JArrayType isArray = classType.isArray(); - if (isArray != null) { - TypeInfoComputed arrayTic = checkArrayInstantiable(localLogger, isArray, path, - problems); - assert getTypeInfoComputed(classType, path, false) != null; - return arrayTic; - } - - if (classType == typeOracle.getJavaLangObject()) { - /* - * Report an error if the type is or erases to Object since this violates - * our restrictions on RPC. Should be fatal, but I worry users may have - * Object-using code they can't readily get out of the class hierarchy. - */ - problems.add(classType, - "In order to produce smaller client-side code, 'Object' is not " + - "allowed; please use a more specific type", Priority.DEFAULT); - tic = getTypeInfoComputed(classType, path, true); - tic.setInstantiable(false); - return tic; - } - - if (classType.isRawType() != null) { - localLogger.log( - TreeLogger.DEBUG, - "Type '" - + classType.getQualifiedSourceName() - + "' should be parameterized to help the compiler produce the smallest code size possible for your module", - null); - } - - JClassType originalType = (JClassType) type; - - // TreeLogger subtypesLogger = localLogger.branch(TreeLogger.DEBUG, - // "Analyzing subclasses:", null); - tic = getTypeInfoComputed(classType, path, true); - boolean anySubtypes = checkSubtypes(localLogger, originalType, - tic.getInstantiableTypes(), path, problems); - if (!tic.isDone()) { - tic.setInstantiableSubtypes(anySubtypes); - tic.setInstantiable(false); - } - return tic; - } - - int getTypeParameterExposure(JGenericType type, int index) { - return getFlowInfo(type, index).getExposure(); - } - - /** - * Returns true if the fields of the type should be considered - * for serialization. - * - * Default access to allow for testing. - */ - boolean shouldConsiderFieldsForSerialization(JClassType type, - ProblemReport problems) { - return shouldConsiderFieldsForSerialization(type, typeFilter, - problems); - } - - /** - * Consider any subtype of java.lang.Object which qualifies for serialization. - * - * @param logger - */ - private void checkAllSubtypesOfObject(TreeLogger logger, TypePath parent, - ProblemReport problems) { - if (alreadyCheckedObject) { - return; - } - alreadyCheckedObject = true; - - /* - * This will pull in the world and the set of serializable types will be - * larger than it needs to be. We exclude types that do not qualify for - * serialization to avoid generating false errors due to types that do not - * qualify for serialization and have no serializable subtypes. - */ - TreeLogger localLogger = logger.branch(TreeLogger.WARN, - "Checking all subtypes of Object which qualify for serialization", null); - JClassType[] allTypes = typeOracle.getJavaLangObject().getSubtypes(); - for (JClassType cls : allTypes) { - if (isDeclaredSerializable(cls)) { - computeTypeInstantiability(localLogger, cls, - TypePaths.createSubtypePath(parent, cls, - typeOracle.getJavaLangObject()), problems); - } - } - } - - private TypeInfoComputed checkArrayInstantiable(TreeLogger logger, JArrayType array, - TypePath path, ProblemReport problems) { - - JType leafType = array.getLeafType(); - JWildcardType leafWild = leafType.isWildcard(); - if (leafWild != null) { - JArrayType arrayType = getArrayType(typeOracle, array.getRank(), - leafWild.getUpperBound()); - return checkArrayInstantiable(logger, arrayType, path, problems); - } - - JClassType leafClass = leafType.isClassOrInterface(); - JTypeParameter isLeafTypeParameter = leafType.isTypeParameter(); - if (isLeafTypeParameter != null - && !typeParametersInRootTypes.contains(isLeafTypeParameter)) { - // Don't deal with non root type parameters, but make a TIC entry to - // save time if it recurs. We assume they're indirectly instantiable. - TypeInfoComputed tic = getTypeInfoComputed(array, path, true); - tic.setInstantiableSubtypes(true); - tic.setInstantiable(false); - return tic; - } - - if (!isAllowedByFilter(array, problems)) { - // Don't deal with filtered out types either, but make a TIC entry to - // save time if it recurs. We assume they're not instantiable. - TypeInfoComputed tic = getTypeInfoComputed(array, path, true); - tic.setInstantiable(false); - return tic; - } - - TypeInfoComputed tic = getTypeInfoComputed(array, path, true); - if (tic.isDone()) { - return tic; - } else if (tic.isPendingInstantiable()) { - return tic; - } - tic.setPendingInstantiable(); - - TreeLogger branch = logger.branch(TreeLogger.DEBUG, - "Analyzing component type:", null); - - TypeInfoComputed leafTic = computeTypeInstantiability(branch, leafType, - TypePaths.createArrayComponentPath(array, path), problems); - boolean succeeded = leafTic.hasInstantiableSubtypes(); - if (succeeded) { - if (leafClass == null) { - assert leafType.isPrimitive() != null; - markArrayTypesInstantiable(leafType, array.getRank(), path); - } else { - TreeLogger covariantArrayLogger = logger.branch(TreeLogger.DEBUG, - "Covariant array types"); - - /* - * Compute covariant arrays for arrays of reference types. - */ - for (JClassType instantiableType : TypeHierarchyUtils.getAllTypesBetweenRootTypeAndLeaves( - leafClass, leafTic.getInstantiableTypes())) { - if (!isAccessibleToSerializer(instantiableType)) { - // Skip types that are not accessible from a serializer - continue; - } - - covariantArrayLogger.branch( - TreeLogger.DEBUG, - getArrayType(typeOracle, array.getRank(), instantiableType).getParameterizedQualifiedSourceName()); - - markArrayTypesInstantiable(instantiableType, array.getRank(), path); - } - } - } - - tic.setInstantiable(succeeded); - return tic; - } - - /** - * Returns true if the declared fields of this type are all - * instantiable. As a side-effect it fills in {@link TypeInfoComputed} for all - * necessary types. - */ - private boolean checkDeclaredFields(TreeLogger logger, - TypeInfoComputed typeInfo, TypePath parent, ProblemReport problems) { - - JClassType classOrInterface = (JClassType) typeInfo.getType(); - if (classOrInterface.isEnum() != null) { - // The fields of an enum are never serialized; they are always okay. - return true; - } - - JClassType baseType = getBaseType(classOrInterface); - - boolean allSucceeded = true; - // TODO: Propagating the constraints will produce better results as long - // as infinite expansion can be avoided in the process. - JField[] fields = baseType.getFields(); - if (fields.length > 0) { - TreeLogger localLogger = logger.branch(TreeLogger.DEBUG, - "Analyzing the fields of type '" - + classOrInterface.getParameterizedQualifiedSourceName() - + "' that qualify for serialization", null); - - for (JField field : fields) { - if (!shouldConsiderForSerialization(localLogger, - suppressNonStaticFinalFieldWarnings, field)) { - continue; - } - - TreeLogger fieldLogger = localLogger.branch(TreeLogger.DEBUG, - field.toString(), null); - JType fieldType = field.getType(); - - TypePath path = TypePaths.createFieldPath(parent, field); - if (typeInfo.isManuallySerializable() - && fieldType.getLeafType() == typeOracle.getJavaLangObject()) { - checkAllSubtypesOfObject(fieldLogger.branch(TreeLogger.WARN, - "Object was reached from a manually serializable type", null), - path, problems); - } else { - allSucceeded &= computeTypeInstantiability(fieldLogger, fieldType, path, - problems).hasInstantiableSubtypes(); - } - } - } - - boolean succeeded = allSucceeded || typeInfo.isManuallySerializable(); - if (succeeded) { - typeInfo.setFieldSerializable(); - } - - return succeeded; - } - - private boolean checkSubtype(TreeLogger logger, JClassType classOrInterface, - JClassType originalType, TypePath parent, ProblemReport problems) { - if (classOrInterface.isEnum() != null) { - // The fields of an enum are never serialized; they are always okay. - return true; - } - - JParameterizedType isParameterized = classOrInterface.isParameterized(); - if (isParameterized != null) { - if (isRawMapOrRawCollection(classOrInterface)) { - /* - * Backwards compatibility. Raw collections or maps force all object - * subtypes to be considered. - */ - checkAllSubtypesOfObject(logger, parent, problems); - } else { - TreeLogger paramsLogger = logger.branch(TreeLogger.DEBUG, - "Checking parameters of '" - + isParameterized.getParameterizedQualifiedSourceName() + "'"); - - for (JTypeParameter param : isParameterized.getBaseType().getTypeParameters()) { - if (!checkTypeArgument(paramsLogger, isParameterized.getBaseType(), - param.getOrdinal(), - isParameterized.getTypeArgs()[param.getOrdinal()], parent, - problems)) { - return false; - } - } - } - } - - // Check all super type fields first (recursively). - JClassType superType = classOrInterface.getSuperclass(); - if (superType != null && superType.isRawType() != null) { - superType = superType.isRawType().asParameterizedByWildcards(); - } - - if (superType != null && isDeclaredSerializable(superType)) { - superType = constrainTypeBy(superType, originalType); - if (superType == null) { - return false; - } - - boolean superTypeOk = false; - superTypeOk = checkSubtype(logger, superType, originalType, - TypePaths.createSupertypePath(parent, superType, classOrInterface), - problems); - - /* - * If my super type did not check out, then I am not instantiable and we - * should error out... UNLESS I amdirectly serializable myself, in which - * case it's ok for me to be the root of a new instantiable hierarchy. - */ - if (!superTypeOk && !isDirectlySerializable(classOrInterface)) { - return false; - } - } - - TypeInfoComputed tic = getTypeInfoComputed(classOrInterface, parent, true); - return checkDeclaredFields(logger, tic, parent, problems); - } - - /** - * Returns true if this type or one of its subtypes is - * instantiable relative to a known base type. - */ - private boolean checkSubtypes(TreeLogger logger, JClassType originalType, - Set instSubtypes, TypePath path, ProblemReport problems) { - JClassType baseType = getBaseType(originalType); - TreeLogger computationLogger = logger.branch(TreeLogger.DEBUG, - "Finding possibly instantiable subtypes"); - List candidates = getPossiblyInstantiableSubtypes( - computationLogger, baseType, problems); - boolean anySubtypes = false; - - TreeLogger verificationLogger = logger.branch(TreeLogger.DEBUG, - "Verifying instantiability"); - for (JClassType candidate : candidates) { - if (getBaseType(candidate) == baseType - && originalType.isRawType() == null) { - // Don't rely on the constrainer when we have perfect information. - candidate = originalType; - } else { - candidate = constrainTypeBy(candidate, originalType); - if (candidate == null) { - continue; - } - } - - if (!isAllowedByFilter(candidate, problems)) { - continue; - } - - TypePath subtypePath = TypePaths.createSubtypePath(path, candidate, - originalType); - TypeInfoComputed tic = getTypeInfoComputed(candidate, subtypePath, true); - if (tic.isDone()) { - if (tic.isInstantiable()) { - anySubtypes = true; - instSubtypes.add(candidate); - } - continue; - } else if (tic.isPendingInstantiable()) { - anySubtypes = true; - instSubtypes.add(candidate); - continue; - } - tic.setPendingInstantiable(); - - TreeLogger subtypeLogger = verificationLogger.branch(TreeLogger.DEBUG, - candidate.getParameterizedQualifiedSourceName()); - boolean instantiable = checkSubtype(subtypeLogger, candidate, - originalType, subtypePath, problems); - anySubtypes |= instantiable; - tic.setInstantiable(instantiable); - - if (instantiable) { - subtypeLogger.branch(TreeLogger.DEBUG, "Is instantiable"); - } - - // Note we are leaving hasInstantiableSubtypes() as false which might be - // wrong but it is only used by arrays and thus it will never be looked at - // for this tic. - if (instantiable && instSubtypes != null) { - instSubtypes.add(candidate); - } - } - - return anySubtypes; - } - - /** - * Check the argument to a parameterized type to see if it will make the type - * it is applied to be serializable. As a side effect, populates - * {@link #typeToTypeInfoComputed} in the same way as - * {@link #checkTypeInstantiable(TreeLogger, JType, boolean)}. - * - * @param logger - * @param baseType - The generic type the parameter is on - * @param paramIndex - The index of the parameter in the generic type - * @param typeArg - An upper bound on the actual argument being applied to the - * generic type - * - * @return Whether the a parameterized type can be serializable if - * baseType is the base type and the - * paramIndexth type argument is a subtype of - * typeArg. - */ - private boolean checkTypeArgument(TreeLogger logger, JGenericType baseType, - int paramIndex, JClassType typeArg, TypePath parent, - ProblemReport problems) { - JWildcardType isWildcard = typeArg.isWildcard(); - if (isWildcard != null) { - return checkTypeArgument(logger, baseType, paramIndex, - isWildcard.getUpperBound(), parent, problems); - } - - JArrayType typeArgAsArray = typeArg.isArray(); - if (typeArgAsArray != null) { - JTypeParameter parameterOfTypeArgArray = typeArgAsArray.getLeafType().isTypeParameter(); - if (parameterOfTypeArgArray != null) { - JGenericType declaringClass = parameterOfTypeArgArray.getDeclaringClass(); - if (declaringClass != null) { - TypeParameterFlowInfo flowInfoForArrayParam = getFlowInfo( - declaringClass, parameterOfTypeArgArray.getOrdinal()); - TypeParameterFlowInfo otherFlowInfo = getFlowInfo(baseType, - paramIndex); - if (otherFlowInfo.getExposure() >= 0 - && otherFlowInfo.isTransitivelyAffectedBy(flowInfoForArrayParam)) { - problems.add(baseType, - "Cannot serialize type '" - + baseType.getParameterizedQualifiedSourceName() - + "' when given an argument of type '" - + typeArg.getParameterizedQualifiedSourceName() - + "' because it appears to require serializing arrays " - + "of unbounded dimension", Priority.DEFAULT); - return false; - } - } - } - } - - TypePath path = TypePaths.createTypeArgumentPath(parent, baseType, - paramIndex, typeArg); - int exposure = getTypeParameterExposure(baseType, paramIndex); - switch (exposure) { - case TypeParameterExposureComputer.EXPOSURE_DIRECT: { - TreeLogger branch = logger.branch( - TreeLogger.DEBUG, - "Checking type argument " - + paramIndex - + " of type '" - + baseType.getParameterizedQualifiedSourceName() - + "' because it is directly exposed in this type or in one of its subtypes"); - return computeTypeInstantiability(branch, typeArg, path, problems).hasInstantiableSubtypes() - || mightNotBeExposed(baseType, paramIndex); - } - case TypeParameterExposureComputer.EXPOSURE_NONE: - // Ignore this argument - logger.log(Type.DEBUG, "Ignoring type argument " + paramIndex - + " of type '" + baseType.getParameterizedQualifiedSourceName() - + "' because it is not exposed in this or any subtype"); - return true; - - default: { - assert (exposure >= TypeParameterExposureComputer.EXPOSURE_MIN_BOUNDED_ARRAY); - problems.add(getArrayType(typeOracle, exposure, typeArg), - "Checking type argument " - + paramIndex - + " of type '" - + baseType.getParameterizedQualifiedSourceName() - + "' because it is exposed as an array with a maximum dimension of " - + exposure + " in this type or one of its subtypes", - Priority.AUXILIARY); - return computeTypeInstantiability(logger, - getArrayType(typeOracle, exposure, typeArg), path, problems).hasInstantiableSubtypes() - || mightNotBeExposed(baseType, paramIndex); - } - } - } - - /** - * If type's base class does not inherit from - * superType's base class, then return type - * unchanged. If it does, then return a subtype of type that - * includes all values in both type and superType. - * If there are definitely no such values, return null. - */ - private JClassType constrainTypeBy(JClassType type, JClassType superType) { - return typeConstrainer.constrainTypeBy(type, superType); - } - - private TypeParameterFlowInfo getFlowInfo(JGenericType type, int index) { - return typeParameterExposureComputer.computeTypeParameterExposure(type, - index); - } - - /** - * Returns the subtypes of a given base type as parameterized by wildcards. - */ - private List getPossiblyInstantiableSubtypes(TreeLogger logger, - JClassType baseType, ProblemReport problems) { - assert (baseType == getBaseType(baseType)); - - List possiblyInstantiableTypes = new ArrayList(); - if (baseType == typeOracle.getJavaLangObject()) { - return possiblyInstantiableTypes; - } - - List candidates = new ArrayList(); - candidates.add(baseType); - List subtypes = Arrays.asList(baseType.getSubtypes()); - candidates.addAll(subtypes); - - for (JClassType subtype : candidates) { - JClassType subtypeBase = getBaseType(subtype); - if (maybeInstantiable(logger, subtypeBase, problems)) { - /* - * Convert the generic type into a parameterization that only includes - * wildcards. - */ - JGenericType isGeneric = subtype.isGenericType(); - if (isGeneric != null) { - subtype = isGeneric.asParameterizedByWildcards(); - } else { - assert (subtype instanceof JRealClassType); - } - - possiblyInstantiableTypes.add(subtype); - } - } - - if (possiblyInstantiableTypes.size() == 0) { - String possibilities[] = new String[candidates.size()]; - for (int i = 0; i < possibilities.length; i++) { - JClassType subtype = candidates.get(i); - String worstMessage = problems.getWorstMessageForType(subtype); - if (worstMessage == null) { - possibilities[i] = " subtype " + - subtype.getParameterizedQualifiedSourceName() + - " is not instantiable"; - } else { - // message with have the form "FQCN some-problem-description" - possibilities[i] = " subtype " + worstMessage; - } - } - problems.add(baseType, baseType.getParameterizedQualifiedSourceName() - + " has no available instantiable subtypes.", Priority.DEFAULT, - possibilities); - } - return possiblyInstantiableTypes; - } - - private TypeInfoComputed getTypeInfoComputed(JType type, TypePath path, - boolean createIfNeeded) { - TypeInfoComputed tic = typeToTypeInfoComputed.get(type); - if (tic == null && createIfNeeded) { - tic = new TypeInfoComputed(type, path); - typeToTypeInfoComputed.put(type, tic); - } - return tic; - } - - private boolean isAllowedByFilter(JClassType classType, - ProblemReport problems) { - return isAllowedByFilter(typeFilter, classType, problems); - } - - /** - * Returns true if the type is Collection or - * Map. - */ - private boolean isRawMapOrRawCollection(JClassType type) { - if (type.asParameterizationOf(collectionClass) == collectionClass.asParameterizedByWildcards()) { - return true; - } - - if (type.asParameterizationOf(mapClass) == mapClass.asParameterizedByWildcards()) { - return true; - } - - return false; - } - - private void logPath(TreeLogger logger, TypePath path) { - if (path == null) { - return; - } - - logger.log(TreeLogger.DEBUG, path.toString()); - logPath(logger, path.getParent()); - } - - private void logReachableTypes(TreeLogger logger) { - PrintWriter printWriter = null; - if (logOutputStream != null) { - // Route the TreeLogger output to an output stream. - printWriter = new PrintWriter(logOutputStream); - PrintWriterTreeLogger printWriterTreeLogger = new PrintWriterTreeLogger( - printWriter); - printWriterTreeLogger.setMaxDetail(TreeLogger.ALL); - logger = printWriterTreeLogger; - } - - logger.log(TreeLogger.DEBUG, "Reachable types computed on: " - + new Date().toString()); - Set keySet = typeToTypeInfoComputed.keySet(); - JType[] types = keySet.toArray(new JType[0]); - Arrays.sort(types, JTYPE_COMPARATOR); - - for (JType type : types) { - TypeInfoComputed tic = typeToTypeInfoComputed.get(type); - assert (tic != null); - - TreeLogger typeLogger = logger.branch(TreeLogger.DEBUG, - tic.getType().getParameterizedQualifiedSourceName()); - TreeLogger serializationStatus = typeLogger.branch(TreeLogger.DEBUG, - "Serialization status"); - if (tic.isInstantiable()) { - serializationStatus.branch(TreeLogger.DEBUG, "Instantiable"); - } else { - if (tic.isFieldSerializable()) { - serializationStatus.branch(TreeLogger.DEBUG, "Field serializable"); - } else { - serializationStatus.branch(TreeLogger.DEBUG, "Not serializable"); - } - } - - TreeLogger pathLogger = typeLogger.branch(TreeLogger.DEBUG, "Path"); - - logPath(pathLogger, tic.getPath()); - logger.log(TreeLogger.DEBUG, ""); - } - - if (printWriter != null) { - printWriter.flush(); - } - } - - /** - * Mark arrays of leafType as instantiable, for arrays of - * dimension up to maxRank. - */ - private void markArrayTypesInstantiable(JType leafType, int maxRank, - TypePath path) { - for (int rank = 1; rank <= maxRank; ++rank) { - JArrayType covariantArray = getArrayType(typeOracle, rank, leafType); - - TypeInfoComputed covariantArrayTic = getTypeInfoComputed(covariantArray, - path, true); - covariantArrayTic.setInstantiable(true); - } - } - - private boolean maybeInstantiable(TreeLogger logger, JClassType type, - ProblemReport problems) { - boolean success = canBeInstantiated(type, problems) - && shouldConsiderFieldsForSerialization(type, problems); - if (success) { - logger.log(TreeLogger.DEBUG, - type.getParameterizedQualifiedSourceName() + " might be instantiable"); - } - return success; - } - - private boolean mightNotBeExposed(JGenericType baseType, int paramIndex) { - TypeParameterFlowInfo flowInfo = getFlowInfo(baseType, paramIndex); - return flowInfo.getMightNotBeExposed() || isManuallySerializable(baseType); - } - - /** - * Remove serializable types that were visited due to speculative paths but - * are not really needed for serialization. - * - * NOTE: This is currently much more limited than it should be. For example, a - * path sensitive prune could remove instantiable types also. - */ - private void pruneUnreachableTypes() { - /* - * Record all supertypes of any instantiable type, whether or not they are - * field serialziable. - */ - Set supersOfInstantiableTypes = new LinkedHashSet(); - for (TypeInfoComputed tic : typeToTypeInfoComputed.values()) { - if (tic.isInstantiable() && tic.getType() instanceof JClassType) { - JClassType type = (JClassType) tic.getType().getErasedType(); - JClassType sup = type; - while (sup != null) { - supersOfInstantiableTypes.add(sup.getErasedType()); - sup = sup.getErasedType().getSuperclass(); - } - } - } - - /* - * Record any field serializable type that is not in the supers of any - * instantiable type. - */ - Set toKill = new LinkedHashSet(); - for (TypeInfoComputed tic : typeToTypeInfoComputed.values()) { - if (tic.isFieldSerializable() - && !supersOfInstantiableTypes.contains(tic.getType().getErasedType())) { - toKill.add(tic.getType()); - } - } - - /* - * Remove any field serializable supers that cannot be reached from an - * instantiable type. - */ - for (JType type : toKill) { - typeToTypeInfoComputed.remove(type); - } - } -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/SerializableTypeOracleImpl.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/SerializableTypeOracleImpl.java deleted file mode 100755 index 7e6c4526f18..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/SerializableTypeOracleImpl.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2007 Google Inc. - * - * 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 de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc; - -import com.google.gwt.core.ext.typeinfo.JClassType; -import com.google.gwt.core.ext.typeinfo.JType; - -import java.util.Set; - -final class SerializableTypeOracleImpl implements SerializableTypeOracle { - - private final Set possiblyInstantiatedTypes; - private final Set serializableTypesSet; - - public SerializableTypeOracleImpl(Set serializableTypes, - Set possiblyInstantiatedTypes) { - - serializableTypesSet = serializableTypes; - this.possiblyInstantiatedTypes = possiblyInstantiatedTypes; - } - - public JType[] getSerializableTypes() { - return serializableTypesSet.toArray(new JType[serializableTypesSet.size()]); - } - - /** - * Returns true if the type's fields can be serializede. - */ - public boolean isSerializable(JType type) { - return serializableTypesSet.contains(type); - } - - /** - * Returns true if the type can be serialized and then - * instantiated on the other side. - */ - public boolean maybeInstantiated(JType type) { - return possiblyInstantiatedTypes.contains(type); - } -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/SerializationUtils.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/SerializationUtils.java deleted file mode 100755 index 784866b3f1e..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/SerializationUtils.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Copyright 2008 Google Inc. - * - * 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 de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc; - -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.zip.CRC32; - -import com.google.gwt.core.ext.TreeLogger; -import com.google.gwt.core.ext.typeinfo.JArrayType; -import com.google.gwt.core.ext.typeinfo.JClassType; -import com.google.gwt.core.ext.typeinfo.JField; -import com.google.gwt.core.ext.typeinfo.JParameterizedType; -import com.google.gwt.core.ext.typeinfo.JType; -import com.google.gwt.core.ext.typeinfo.TypeOracle; -import com.google.gwt.dev.util.Util; - -/** - * Utilities used for implementing serialization. - */ -public class SerializationUtils { - static final Comparator FIELD_COMPARATOR = new Comparator() { - public int compare(JField f1, JField f2) { - return f1.getName().compareTo(f2.getName()); - } - }; - static final String GENERATED_FIELD_SERIALIZER_SUFFIX = "_FieldSerializer"; - static final String TYPE_SERIALIZER_SUFFIX = "_TypeSerializer"; - static final Set TYPES_WHOSE_IMPLEMENTATION_IS_EXCLUDED_FROM_SIGNATURES = new HashSet(); - - static { - TYPES_WHOSE_IMPLEMENTATION_IS_EXCLUDED_FROM_SIGNATURES.add("java.lang.Boolean"); - TYPES_WHOSE_IMPLEMENTATION_IS_EXCLUDED_FROM_SIGNATURES.add("java.lang.Byte"); - TYPES_WHOSE_IMPLEMENTATION_IS_EXCLUDED_FROM_SIGNATURES.add("java.lang.Character"); - TYPES_WHOSE_IMPLEMENTATION_IS_EXCLUDED_FROM_SIGNATURES.add("java.lang.Double"); - TYPES_WHOSE_IMPLEMENTATION_IS_EXCLUDED_FROM_SIGNATURES.add("java.lang.Exception"); - TYPES_WHOSE_IMPLEMENTATION_IS_EXCLUDED_FROM_SIGNATURES.add("java.lang.Float"); - TYPES_WHOSE_IMPLEMENTATION_IS_EXCLUDED_FROM_SIGNATURES.add("java.lang.Integer"); - TYPES_WHOSE_IMPLEMENTATION_IS_EXCLUDED_FROM_SIGNATURES.add("java.lang.Long"); - TYPES_WHOSE_IMPLEMENTATION_IS_EXCLUDED_FROM_SIGNATURES.add("java.lang.Object"); - TYPES_WHOSE_IMPLEMENTATION_IS_EXCLUDED_FROM_SIGNATURES.add("java.lang.Short"); - TYPES_WHOSE_IMPLEMENTATION_IS_EXCLUDED_FROM_SIGNATURES.add("java.lang.String"); - TYPES_WHOSE_IMPLEMENTATION_IS_EXCLUDED_FROM_SIGNATURES.add("java.lang.Throwable"); - } - - /** - * Returns the set of fields that are serializable for a given class type. - * This method does not consider any superclass fields. - * - * @param classType the class for which we want serializable fields - * @return array of fields that meet the serialization criteria. - */ - public static JField[] getSerializableFields(TypeOracle typeOracle, - JClassType classType) { - assert (classType != null); - - List fields = new ArrayList(); - JField[] declFields = classType.getFields(); - assert (declFields != null); - for (JField field : declFields) { - if (SerializableTypeOracleBuilder.shouldConsiderForSerialization( - TreeLogger.NULL, true, field)) { - fields.add(field); - } - } - - Collections.sort(fields, FIELD_COMPARATOR); - return fields.toArray(new JField[fields.size()]); - } - - /** - * Returns the name of the field serializer for a particular type. This name - * can be either the name of a custom field serializer or that of a generated - * field serializer. If the type is not serializable then it can return null. - * - * @param type the type that is going to be serialized - * - * @return the fully qualified name of the field serializer for the given type - */ - static String getFieldSerializerName(TypeOracle typeOracle, JType type) { - JClassType customSerializer = SerializableTypeOracleBuilder.findCustomFieldSerializer( - typeOracle, type); - if (customSerializer != null) { - return customSerializer.getQualifiedSourceName(); - } - - assert (type.isClassOrInterface() != null || type.isArray() != null); - JClassType classType = (JClassType) type; - String[] name = Shared.synthesizeTopLevelClassName(classType, - SerializationUtils.GENERATED_FIELD_SERIALIZER_SUFFIX); - if (name[0].length() > 0) { - String serializerName = name[0] + "." + name[1]; - if (SerializableTypeOracleBuilder.isInStandardJavaPackage(type.getQualifiedSourceName())) { - /* - * Don't generate code into java packages. If you do hosted mode - * CompilingClassLoader will fail to resolve references to the generated - * code. - */ - serializerName = "com.google.gwt.user.client.rpc.core." - + serializerName; - } - - return serializerName; - } else { - return name[1]; - } - } - - /** - * Returns the serialization signature for a type. - * - * @param instanceType - * @return a string representing the serialization signature of a type - */ - public static String getSerializationSignature(TypeOracle typeOracle, JType type) - throws RuntimeException { - CRC32 crc = new CRC32(); - - try { - generateSerializationSignature(typeOracle, type, crc); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException( - "Could not compute the serialization signature", e); - } - - return Long.toString(crc.getValue()); - } - - /** - * Returns the qualified name of the type serializer class for the given - * service interface. - * - * @param serviceIntf service interface - * @return name of the type serializer that handles the service interface - */ - public static String getTypeSerializerQualifiedName(JClassType serviceIntf) - throws IllegalArgumentException { - if (serviceIntf.isInterface() == null) { - throw new IllegalArgumentException(serviceIntf.getQualifiedSourceName() - + " is not a service interface"); - } - - String[] name = Shared.synthesizeTopLevelClassName(serviceIntf, - TYPE_SERIALIZER_SUFFIX); - if (name[0].length() > 0) { - return name[0] + "." + name[1]; - } else { - return name[1]; - } - } - - /** - * Returns the simple name of the type serializer class for the given service - * interface. - * - * @param serviceIntf service interface - * @return the simple name of the type serializer class - */ - static String getTypeSerializerSimpleName(TypeOracle typeOracle, - JClassType serviceIntf) throws IllegalArgumentException { - if (serviceIntf.isInterface() == null) { - throw new IllegalArgumentException(serviceIntf.getQualifiedSourceName() - + " is not a service interface"); - } - - String[] name = Shared.synthesizeTopLevelClassName(serviceIntf, - TYPE_SERIALIZER_SUFFIX); - return name[1]; - } - - private static boolean excludeImplementationFromSerializationSignature( - JType instanceType) { - if (TYPES_WHOSE_IMPLEMENTATION_IS_EXCLUDED_FROM_SIGNATURES.contains(instanceType.getQualifiedSourceName())) { - return true; - } - - return false; - } - - private static void generateSerializationSignature(TypeOracle typeOracle, - JType type, CRC32 crc) throws UnsupportedEncodingException { - JParameterizedType parameterizedType = type.isParameterized(); - if (parameterizedType != null) { - generateSerializationSignature(typeOracle, - parameterizedType.getRawType(), crc); - - return; - } - - String serializedTypeName = type.getQualifiedBinaryName(); - crc.update(serializedTypeName.getBytes(Util.DEFAULT_ENCODING)); - - if (excludeImplementationFromSerializationSignature(type)) { - return; - } - - JClassType customSerializer = SerializableTypeOracleBuilder.findCustomFieldSerializer( - typeOracle, type); - if (customSerializer != null) { - generateSerializationSignature(typeOracle, customSerializer, crc); - } else if (type.isArray() != null) { - JArrayType isArray = type.isArray(); - generateSerializationSignature(typeOracle, isArray.getComponentType(), - crc); - } else if (type.isClassOrInterface() != null) { - JClassType isClassOrInterface = type.isClassOrInterface(); - JField[] fields = getSerializableFields(typeOracle, isClassOrInterface); - for (JField field : fields) { - assert (field != null); - - crc.update(field.getName().getBytes(Util.DEFAULT_ENCODING)); - crc.update(field.getType().getQualifiedBinaryName().getBytes( - Util.DEFAULT_ENCODING)); - } - - JClassType superClass = isClassOrInterface.getSuperclass(); - if (superClass != null) { - generateSerializationSignature(typeOracle, superClass, crc); - } - } - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/ServiceInterfaceProxyGenerator.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/ServiceInterfaceProxyGenerator.java deleted file mode 100755 index dc316cd2b2d..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/ServiceInterfaceProxyGenerator.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2007 Google Inc. - * - * 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 de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc; - -import com.google.gwt.core.ext.Generator; -import com.google.gwt.core.ext.GeneratorContext; -import com.google.gwt.core.ext.TreeLogger; -import com.google.gwt.core.ext.UnableToCompleteException; -import com.google.gwt.core.ext.typeinfo.JClassType; -import com.google.gwt.core.ext.typeinfo.TypeOracle; - -/** - * Generator for producing the asynchronous version of a - * {@link com.google.gwt.user.client.rpc.RemoteService RemoteService} interface. - */ -public class ServiceInterfaceProxyGenerator extends Generator { - - @Override - public String generate(TreeLogger logger, GeneratorContext ctx, - String requestedClass) throws UnableToCompleteException { - - TypeOracle typeOracle = ctx.getTypeOracle(); - assert (typeOracle != null); - - JClassType remoteService = typeOracle.findType(requestedClass); - if (remoteService == null) { - logger.log(TreeLogger.ERROR, "Unable to find metadata for type '" - + requestedClass + "'", null); - throw new UnableToCompleteException(); - } - - if (remoteService.isInterface() == null) { - logger.log(TreeLogger.ERROR, remoteService.getQualifiedSourceName() - + " is not an interface", null); - throw new UnableToCompleteException(); - } - - ProxyCreator proxyCreator = createProxyCreator(remoteService); - - TreeLogger proxyLogger = logger.branch(TreeLogger.DEBUG, - "Generating client proxy for remote service interface '" - + remoteService.getQualifiedSourceName() + "'", null); - - return proxyCreator.create(proxyLogger, ctx); - } - - protected ProxyCreator createProxyCreator(JClassType remoteService) { - return new ProxyCreator(remoteService); - } -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/Shared.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/Shared.java deleted file mode 100755 index 2ebb739f18d..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/Shared.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Copyright 2008 Google Inc. - * - * 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 de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc; - -import java.util.Collections; -import java.util.HashSet; -import java.util.Locale; -import java.util.Set; - -import com.google.gwt.core.ext.BadPropertyValueException; -import com.google.gwt.core.ext.ConfigurationProperty; -import com.google.gwt.core.ext.PropertyOracle; -import com.google.gwt.core.ext.SelectionProperty; -import com.google.gwt.core.ext.TreeLogger; -import com.google.gwt.core.ext.typeinfo.JArrayType; -import com.google.gwt.core.ext.typeinfo.JClassType; -import com.google.gwt.core.ext.typeinfo.JParameterizedType; -import com.google.gwt.core.ext.typeinfo.JPrimitiveType; -import com.google.gwt.core.ext.typeinfo.JType; - -public class Shared { - - /** - * Property used to control whether or not the RPC system will emit warnings - * when a type has final fields. - */ - private static final String RPC_PROP_SUPPRESS_NON_STATIC_FINAL_FIELD_WARNINGS = "gwt.suppressNonStaticFinalFieldWarnings"; - - /** - * Multi-valued configuration property used to list classes that are - * (potentially) enhanced with server-only fields, to be handled specially by - * RPC. - */ - private static final String RPC_ENHANCED_CLASSES = "rpc.enhancedClasses"; - - /** - * Capitalizes a name. - * - * @param name the string to be capitalized - * @return the capitalized string - */ - static String capitalize(String name) { - return name.substring(0, 1).toUpperCase(Locale.US) + name.substring(1); - } - - /** - * Returns a Set of names of classes that may be enhanced with extra server-only fields. - * - * @param propertyOracle The propertyOracle used to access the relevant configuration - * property. - * @return a Set of Strings, or null. - */ - static Set getEnhancedTypes(PropertyOracle propertyOracle) { - try { - ConfigurationProperty prop = propertyOracle.getConfigurationProperty(RPC_ENHANCED_CLASSES); - return Collections.unmodifiableSet(new HashSet(prop.getValues())); - } catch (BadPropertyValueException e) { - return null; - } - } - - static String getStreamReadMethodNameFor(JType type) { - return "read" + getCallSuffix(type); - } - - static String getStreamWriteMethodNameFor(JType type) { - return "write" + getCallSuffix(type); - } - - /** - * Returns true if warnings should not be emitted for final - * fields in serializable types. - */ - static boolean shouldSuppressNonStaticFinalFieldWarnings(TreeLogger logger, - PropertyOracle propertyOracle) { - return getBooleanProperty(logger, propertyOracle, - RPC_PROP_SUPPRESS_NON_STATIC_FINAL_FIELD_WARNINGS, false); - } - - /** - * Computes a good name for a class related to the specified type, such that - * the computed name can be a top-level class in the same package as the - * specified type. - * - *

- * This method does not currently check for collisions between the synthesized - * name and an existing top-level type in the same package. It is actually - * tricky to do so, because on subsequent runs, we'll view our own generated - * classes as collisions. There's probably some trick we can use in the future - * to make it totally bulletproof. - *

- * - * @param type the name of the base type, whose name will be built upon to - * synthesize a new type name - * @param suffix a suffix to be used to make the new synthesized type name - * @return an array of length 2 such that the first element is the package - * name and the second element is the synthesized class name - */ - public static String[] synthesizeTopLevelClassName(JClassType type, String suffix) { - // Gets the basic name of the type. If it's a nested type, the type name - // will contains dots. - // - String className; - String packageName; - - JType leafType = type.getLeafType(); - if (leafType.isPrimitive() != null) { - className = leafType.getSimpleSourceName(); - packageName = ""; - } else { - JClassType classOrInterface = leafType.isClassOrInterface(); - assert (classOrInterface != null); - className = classOrInterface.getName(); - packageName = classOrInterface.getPackage().getName(); - } - - JArrayType isArray = type.isArray(); - if (isArray != null) { - className += "_Array_Rank_" + isArray.getRank(); - } - - // Add the meaningful suffix. - // - className += suffix; - - // Make it a top-level name. - // - className = className.replace('.', '_'); - - return new String[] {packageName, className}; - } - - /** - * Determines whether a particular type needs to be cast to become its final - * type. Primitives and Strings do not, as they are read directly as the - * correct type. All other Objects need a cast, except for Object itself. - * - * @param type the type in question - * @return true if the results of a read method must be cast, - * otherwise false. - */ - static boolean typeNeedsCast(JType type) { - return type.isPrimitive() == null - && !type.getQualifiedSourceName().equals("java.lang.String") - && !type.getQualifiedSourceName().equals("java.lang.Object"); - } - - private static boolean getBooleanProperty(TreeLogger logger, - PropertyOracle propertyOracle, String propertyName, boolean defaultValue) { - try { - SelectionProperty prop - = propertyOracle.getSelectionProperty(logger, propertyName); - String propVal = prop.getCurrentValue(); - if (propVal != null && propVal.length() > 0) { - return Boolean.valueOf(propVal); - } - } catch (BadPropertyValueException e) { - // Just return the default value. - } - return defaultValue; - } - - /** - * Gets the suffix needed to make a call for a particular type. For example, - * the int class needs methods named "readInt" and "writeInt". - * - * @param type the type in question - * @return the suffix of the method to call - */ - private static String getCallSuffix(JType type) { - JParameterizedType isParameterized = type.isParameterized(); - if (isParameterized != null) { - return getCallSuffix(isParameterized.getRawType()); - } else if (type.isPrimitive() != null) { - if (type == JPrimitiveType.BOOLEAN) { - return "Boolean"; - } else if (type == JPrimitiveType.BYTE) { - return "Byte"; - } else if (type == JPrimitiveType.CHAR) { - return "Char"; - } else if (type == JPrimitiveType.DOUBLE) { - return "Double"; - } else if (type == JPrimitiveType.FLOAT) { - return "Float"; - } else if (type == JPrimitiveType.INT) { - return "Int"; - } else if (type == JPrimitiveType.LONG) { - return "Long"; - } else if (type == JPrimitiveType.SHORT) { - return "Short"; - } else { - return null; - } - } else if (type.getQualifiedSourceName().equals("java.lang.String")) { - return "String"; - } else { - return "Object"; - } - } -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/TypeConstrainer.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/TypeConstrainer.java deleted file mode 100755 index 6752d4de33b..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/TypeConstrainer.java +++ /dev/null @@ -1,363 +0,0 @@ -/* - * Copyright 2008 Google Inc. - * - * 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 de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; - -import com.google.gwt.core.ext.typeinfo.JArrayType; -import com.google.gwt.core.ext.typeinfo.JClassType; -import com.google.gwt.core.ext.typeinfo.JGenericType; -import com.google.gwt.core.ext.typeinfo.JParameterizedType; -import com.google.gwt.core.ext.typeinfo.JRawType; -import com.google.gwt.core.ext.typeinfo.JRealClassType; -import com.google.gwt.core.ext.typeinfo.JType; -import com.google.gwt.core.ext.typeinfo.JWildcardType; -import com.google.gwt.core.ext.typeinfo.TypeOracle; -import com.google.gwt.dev.javac.typemodel.JTypeParameter; - -/** - * This class defines the method - * {@link #constrainTypeBy(JClassType, JClassType)}. - */ -public class TypeConstrainer { - /** - * Check whether two base types have any subclasses in common. Note: this - * could surely be implemented much more efficiently. - */ - private static boolean baseTypesOverlap(JClassType type1, JClassType type2) { - assert (type1 == getBaseType(type1)); - assert (type2 == getBaseType(type2)); - - if (type1 == type2) { - return true; - } - - HashSet subtypes1 = new HashSet(); - subtypes1.add(type1); - for (JClassType sub1 : type1.getSubtypes()) { - subtypes1.add(getBaseType(sub1)); - } - - List subtypes2 = new ArrayList(); - subtypes2.add(type2); - for (JClassType sub2 : type2.getSubtypes()) { - subtypes2.add(getBaseType(sub2)); - } - - for (JClassType sub2 : subtypes2) { - if (subtypes1.contains(sub2)) { - return true; - } - } - - return false; - } - - private static JClassType getBaseType(JClassType type) { - return SerializableTypeOracleBuilder.getBaseType(type); - } - - private static boolean isRealOrParameterized(JClassType type) { - if (type.isParameterized() != null) { - return true; - } - if (type instanceof JRealClassType) { - return true; - } - return false; - } - - private static com.google.gwt.dev.javac.typemodel.JClassType[] makeArray(com.google.gwt.dev.javac.typemodel.JClassType... classTypes) { - return classTypes; - } - - /** - * Check whether param occurs anywhere within type. - */ - private static boolean occurs(final JTypeParameter param, JClassType type) { - class OccursVisitor extends JTypeVisitor { - boolean foundIt = false; - - @Override - public void endVisit(com.google.gwt.core.ext.typeinfo.JTypeParameter seenParam) { - if (seenParam == param) { - foundIt = true; - } - } - } - - OccursVisitor visitor = new OccursVisitor(); - visitor.accept(type); - return visitor.foundIt; - } - - private int freshTypeVariableCounter; - - private final TypeOracle typeOracle; - - public TypeConstrainer(TypeOracle typeOracle) { - this.typeOracle = typeOracle; - } - - /** - * Return a subtype of subType that includes all values in both - * subType and superType. The returned type - * must have the same base type as subType. If there are - * definitely no such values, return null. - */ - public JClassType constrainTypeBy(JClassType subType, JClassType superType) { - JParameterizedType superAsParameterized = superType.isParameterized(); - if (superAsParameterized == null) { - // If the supertype is not parameterized, it will not be possible to - // constrain - // the subtype further. - return subType; - } - - // Replace each wildcard in the subType with a fresh type variable. - // These type variables will be the ones that are constrained. - Map constraints = new HashMap(); - JClassType subWithWildcardsReplaced = replaceWildcardsWithFreshTypeVariables( - subType, constraints); - - // Rewrite subType so that it has the same base type as superType. - JParameterizedType subAsParameterized = subWithWildcardsReplaced.asParameterizationOf(superAsParameterized.getBaseType()); - if (subAsParameterized == null) { - // The subtype's base does not inherit from the supertype's base, - // so again no constraint will be possible. - return subType; - } - - // Check the rewritten type against superType - if (!typesMatch(subAsParameterized, superAsParameterized, constraints)) { - // The types are completely incompatible - return null; - } - - // Apply the revised constraints to the original type - return substitute(subWithWildcardsReplaced, constraints); - } - - /** - * Check whether two types can have any values in common. The - * constraints field holds known constraints for type - * parameters that appear in type1; this method may take - * advantage of those constraints in its decision, and it may tighten them so - * long as the tightening does not reject any values from the overlap of the - * two types. - * - * As an invariant, no key in constraints may occur inside any - * value in constraints. - * - * Note that this algorithm looks for overlap matches in the arguments of - * parameterized types rather than looking for exact matches. Looking for - * overlaps simplifies the algorithm but returns true more often than it has - * to. - */ - boolean typesMatch(JClassType type1, JClassType type2, - Map constraints) { - JGenericType type1Generic = type1.isGenericType(); - if (type1Generic != null) { - return typesMatch(type1Generic.asParameterizedByWildcards(), type2, - constraints); - } - - JGenericType type2Generic = type2.isGenericType(); - if (type2Generic != null) { - return typesMatch(type1, type2Generic.asParameterizedByWildcards(), - constraints); - } - - JWildcardType type1Wild = type1.isWildcard(); - if (type1Wild != null) { - return typesMatch(type1Wild.getUpperBound(), type2, constraints); - } - - JWildcardType type2Wild = type2.isWildcard(); - if (type2Wild != null) { - return typesMatch(type1, type2Wild.getUpperBound(), constraints); - } - - JRawType type1Raw = type1.isRawType(); - if (type1Raw != null) { - return typesMatch(type1Raw.asParameterizedByWildcards(), type2, - constraints); - } - - JRawType type2Raw = type2.isRawType(); - if (type2Raw != null) { - return typesMatch(type1, type2Raw.asParameterizedByWildcards(), - constraints); - } - - // The following assertions are known to be true, given the tests above. -// assert (type1Generic == null); -// assert (type2Generic == null); -// assert (type1Wild == null); -// assert (type2Wild == null); -// assert (type1Raw == null); -// assert (type2Raw == null); - - if (type1 == type2) { - return true; - } - - if (constraints.containsKey(type1)) { - JTypeParameter type1Parameter = (JTypeParameter) type1; - JClassType type2Class = type2; - JClassType type1Bound = constraints.get(type1Parameter); - assert (!occurs(type1Parameter, type1Bound)); - if (!typesMatch(type1Bound, type2, constraints)) { - return false; - } - - if (type1Bound.isAssignableFrom(type2Class)) { - constraints.put(type1Parameter, type2Class); - } - } - - if (type1 == typeOracle.getJavaLangObject()) { - return true; - } - - if (type2 == typeOracle.getJavaLangObject()) { - return true; - } - - com.google.gwt.core.ext.typeinfo.JTypeParameter type1Param = type1.isTypeParameter(); - if (type1Param != null) { - // It would be nice to check that type1Param's bound is a match - // for type2, but that can introduce infinite recursions. - return true; - } - - com.google.gwt.core.ext.typeinfo.JTypeParameter type2Param = type2.isTypeParameter(); - if (type2Param != null) { - // It would be nice to check that type1Param's bound is a match - // for type2, but that can introduce infinite recursions. - return true; - } - - JArrayType type1Array = type1.isArray(); - JArrayType type2Array = type2.isArray(); - if (type1Array != null && type2Array != null) { - if (typesMatch(type1Array.getComponentType(), - type2Array.getComponentType(), constraints)) { - return true; - } - } - - if (isRealOrParameterized(type1) && isRealOrParameterized(type2)) { - JClassType baseType1 = getBaseType(type1); - JClassType baseType2 = getBaseType(type2); - JParameterizedType type1Parameterized = type1.isParameterized(); - JParameterizedType type2Parameterized = type2.isParameterized(); - - if (baseType1 == baseType2 && type1Parameterized != null - && type2Parameterized != null) { - // type1 and type2 are parameterized types with the same base type; - // compare their arguments - JClassType[] args1 = type1Parameterized.getTypeArgs(); - JClassType[] args2 = type2Parameterized.getTypeArgs(); - boolean allMatch = true; - for (int i = 0; i < args1.length; i++) { - if (!typesMatch(args1[i], args2[i], constraints)) { - allMatch = false; - } - } - - if (allMatch) { - return true; - } - } else { - // The types have different base types, so just compare the base types - // for overlap. - if (baseTypesOverlap(baseType1, baseType2)) { - return true; - } - } - } - - return false; - } - - /** - * The same as {@link #typesMatch(JClassType, JClassType, Map)}, but - * additionally support primitive types as well as class types. - */ - boolean typesMatch(JType type1, JType type2, - Map constraints) { - if (type1 == type2) { - // This covers the case where both are primitives - return true; - } - - JClassType type1Class = type1.isClassOrInterface(); - JClassType type2Class = type2.isClassOrInterface(); - if (type1Class != null && type2Class != null - && typesMatch(type1Class, type2Class, constraints)) { - return true; - } - - return false; - } - - /** - * Replace all wildcards in type with a fresh type variable. - * For each type variable created, add an entry in constraints - * mapping the type variable to its upper bound. - */ - private JClassType replaceWildcardsWithFreshTypeVariables(JClassType type, - final Map constraints) { - - JModTypeVisitor replacer = new JModTypeVisitor() { - @Override - public void endVisit(JWildcardType wildcardType) { - JTypeParameter newParam = new JTypeParameter("TP$" - + freshTypeVariableCounter++, -1); - newParam.setBounds(makeArray((com.google.gwt.dev.javac.typemodel.JClassType) typeOracle.getJavaLangObject())); - constraints.put(newParam, wildcardType.getUpperBound()); - replacement = newParam; - } - }; - - return replacer.transform(type); - } - - /** - * Substitute all occurrences in type of type parameters in - * constraints for a wildcard bounded by the parameter's entry - * in constraints. If the argument is null, - * return null. - */ - private JClassType substitute(JClassType type, - final Map constraints) { - JModTypeVisitor substituter = new JModTypeVisitor() { - @Override - public void endVisit(com.google.gwt.core.ext.typeinfo.JTypeParameter param) { - JClassType constr = constraints.get(param); - if (constr != null) { - replacement = constr; - } - } - }; - return substituter.transform(type); - } -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/TypeFilter.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/TypeFilter.java deleted file mode 100755 index afcabdd6baf..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/TypeFilter.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2008 Google Inc. - * - * 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 de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc; - -import com.google.gwt.core.ext.typeinfo.JClassType; - -/** - * Used to filter types out of serialization. - */ -public interface TypeFilter { - /** - * Returns the name of this filter. - * - * - * @return the name of this filter - */ - String getName(); - - /** - * Returns true if the type should be included. - * - * @param type - * @return true if the type should be included - */ - boolean isAllowed(JClassType type); -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/TypeHierarchyUtils.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/TypeHierarchyUtils.java deleted file mode 100755 index 8a7723b66eb..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/TypeHierarchyUtils.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright 2008 Google Inc. - * - * 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 de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc; - -import com.google.gwt.core.ext.typeinfo.JClassType; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -/** - * Collection of utility methods for dealing with type hierarchies. - */ -class TypeHierarchyUtils { - - /** - * Returns true if the type directly implements the specified - * interface. The test is done on erased types; any paramaterizations - * supplied in the arguments are ignored. - * - * @param type type to check - * @param intf interface to look for - * @return true if the type directly implements the specified - * interface - */ - public static boolean directlyImplementsInterface(JClassType type, - JClassType intf) { - type = type.getErasedType(); - intf = intf.getErasedType(); - return directlyImplementsInterfaceRecursive(new HashSet(), - type, intf); - } - - /** - * Returns all types on the path from the root type to the serializable - * leaves. - * - * @param root the root type - * @param leaves the set of serializable leaf types - * @return all types on the path from the root type to the serializable leaves - */ - public static List getAllTypesBetweenRootTypeAndLeaves( - JClassType root, Collection leaves) { - Map> adjList = getInvertedTypeHierarchy(root.getErasedType()); - Set types = new HashSet(); - - for (JClassType type : leaves) { - depthFirstSearch(types, adjList, type.getErasedType()); - } - - return Arrays.asList(types.toArray(new JClassType[0])); - } - - /** - * Returns the immediate subtypes of the erased class argument. - */ - public static List getImmediateSubtypes(JClassType clazz) { - List immediateSubtypes = new ArrayList(); - clazz = clazz.getErasedType(); - for (JClassType subclass : clazz.getSubtypes()) { - JClassType superclass = subclass.getSuperclass(); - if (superclass != null) { - superclass = superclass.getErasedType(); - } - - if (superclass == clazz || clazz.isInterface() != null - && directlyImplementsInterface(subclass, clazz)) { - immediateSubtypes.add(subclass); - } - } - - return immediateSubtypes; - } - - private static void addEdge(Map> adjList, - JClassType subclass, JClassType clazz) { - List edges = adjList.get(subclass); - if (edges == null) { - edges = new ArrayList(); - adjList.put(subclass, edges); - } - - edges.add(clazz); - } - - private static void depthFirstSearch(Set seen, - Map> adjList, JClassType type) { - if (seen.contains(type)) { - return; - } - seen.add(type); - - List children = adjList.get(type); - if (children != null) { - for (JClassType child : children) { - if (!seen.contains(child)) { - depthFirstSearch(seen, adjList, child); - } - } - } - } - - private static boolean directlyImplementsInterfaceRecursive( - Set seen, JClassType clazz, JClassType intf) { - assert (clazz.getErasedType() == clazz); - assert (intf.getErasedType() == intf); - - if (clazz == intf) { - return true; - } - - JClassType[] intfImpls = clazz.getImplementedInterfaces(); - - for (JClassType intfImpl : intfImpls) { - intfImpl = intfImpl.getErasedType(); - if (!seen.contains(intfImpl)) { - seen.add(intfImpl); - - if (directlyImplementsInterfaceRecursive(seen, intfImpl, intf)) { - return true; - } - } - } - - return false; - } - - /** - * Given a root type return an adjacency list that is the inverted type - * hierarchy. - */ - private static Map> getInvertedTypeHierarchy( - JClassType root) { - Map> adjList = new HashMap>(); - Set seen = new HashSet(); - Stack queue = new Stack(); - queue.push(root); - while (!queue.isEmpty()) { - JClassType clazz = queue.pop(); - if (seen.contains(clazz)) { - continue; - } - seen.add(clazz); - - List immediateSubtypes = getImmediateSubtypes(clazz); - for (JClassType immediateSubtype : immediateSubtypes) { - // Add an edge from the immediate subtype to the supertype - addEdge(adjList, immediateSubtype, clazz); - queue.push(immediateSubtype); - } - } - - return adjList; - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/TypeParameterExposureComputer.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/TypeParameterExposureComputer.java deleted file mode 100755 index e799a1f0344..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/TypeParameterExposureComputer.java +++ /dev/null @@ -1,428 +0,0 @@ -/* - * Copyright 2008 Google Inc. - * - * 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 de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc; - -import com.google.gwt.core.ext.TreeLogger; -import com.google.gwt.core.ext.typeinfo.JArrayType; -import com.google.gwt.core.ext.typeinfo.JClassType; -import com.google.gwt.core.ext.typeinfo.JField; -import com.google.gwt.core.ext.typeinfo.JGenericType; -import com.google.gwt.core.ext.typeinfo.JParameterizedType; -import com.google.gwt.core.ext.typeinfo.JTypeParameter; - -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.IdentityHashMap; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; -import java.util.Map.Entry; - -/** - * This class is used to compute type parameter exposure using a flow algorithm. - */ -class TypeParameterExposureComputer { - /** - * Helper class for type parameter flow information. - */ - class TypeParameterFlowInfo { - /** - * The class that declares this type parameter. - */ - private final JGenericType baseType; - - /** - * The keys are the set of type parameters that, if exposed, cause this type - * parameter to be exposed. The value for each key is the dimensionality - * that the exposure will cause. If the key is exposed as an array, then the - * dimensionality should be added to the dimensionality that the key is - * already exposed as. - */ - private final Map causesExposure = new LinkedHashMap(); - - private int exposure = EXPOSURE_NONE; - - private final Map isTransitivelyAffectedByCache = new HashMap(); - - /** - * Type parameters that need to be notified when my exposure changes. - */ - private final Set listeners = new LinkedHashSet(); - - private boolean mightNotBeExposed = true; - - /** - * Ordinal of this type parameter. - */ - private final int ordinal; - - private boolean visited; - - TypeParameterFlowInfo(JGenericType baseType, int ordinal) { - this.baseType = baseType; - this.ordinal = ordinal; - } - - public boolean checkDirectExposure() { - boolean didChange = false; - JClassType type = baseType; - while (type != null) { - // any problems should already have been captured by our caller, so we - // make a throw-away ProblemReport here. - if (SerializableTypeOracleBuilder.shouldConsiderFieldsForSerialization( - type, typeFilter, new ProblemReport())) { - JField[] fields = type.getFields(); - for (JField field : fields) { - if (!SerializableTypeOracleBuilder.shouldConsiderForSerialization( - TreeLogger.NULL, true, field)) { - continue; - } - - if (field.getType().getLeafType() == getTypeParameter()) { - /* - * If the type parameter is referenced explicitly or as the leaf - * type of an array, then it will be considered directly exposed. - */ - markExposedAsArray(0); - mightNotBeExposed = false; - didChange = true; - - JArrayType fieldTypeAsArray = field.getType().isArray(); - if (fieldTypeAsArray != null) { - markExposedAsArray(fieldTypeAsArray.getRank()); - } - } - } - } - - /* - * Counting on substitution to propagate the type parameter. - */ - type = type.getSuperclass(); - } - - return didChange; - } - - public Map getCausesExposure() { - return causesExposure; - } - - public int getExposure() { - return exposure; - } - - public Set getListeners() { - return listeners; - } - - /** - * Return whether it is possible for the parameter not to be exposed. For - * example, if a class has one subclass that uses the parameter and another - * that does not, then the parameter is exposed (exposure >= - * EXPOSURE_DIRECT) but this method will return - * false. - */ - public boolean getMightNotBeExposed() { - return mightNotBeExposed; - } - - /** - * Determine whether there is an infinite array exposure if this type - * parameter is used in an array type which is then passed as an actual type - * argument for the formal type parameter other. - */ - public boolean infiniteArrayExpansionPathBetween(TypeParameterFlowInfo other) { - Integer dimensionDelta = getCausesExposure().get(other); - if (dimensionDelta == null) { - return false; - } - return dimensionDelta > 0 && other.isTransitivelyAffectedBy(this); - } - - @Override - public String toString() { - return getTypeParameter().getName() + " in " + baseType.getName(); - } - - public boolean updateFlowInfo() { - boolean didChange = false; - if (!wasVisited()) { - didChange |= initializeExposure(); - markVisited(); - } - - for (Entry entry : getCausesExposure().entrySet()) { - TypeParameterFlowInfo info2 = entry.getKey(); - int dimensionDelta = entry.getValue(); - if (info2.getExposure() >= 0) { - if (!infiniteArrayExpansionPathBetween(info2)) { - didChange |= markExposedAsArray(dimensionDelta - + info2.getExposure()); - } - } - } - - return didChange; - } - - void addListener(TypeParameterFlowInfo listener) { - listeners.add(listener); - } - - JTypeParameter getTypeParameter() { - return baseType.getTypeParameters()[ordinal]; - } - - boolean initializeExposure() { - computeIndirectExposureCauses(); - return checkDirectExposure(); - } - - boolean isTransitivelyAffectedBy(TypeParameterFlowInfo flowInfo) { - Boolean result = isTransitivelyAffectedByCache.get(flowInfo); - if (result != null) { - return result; - } - - HashSet affectedBy = new HashSet(); - Set affectedByWorklist = new LinkedHashSet(); - affectedByWorklist.add(this); - - result = false; - while (!affectedByWorklist.isEmpty()) { - TypeParameterFlowInfo currFlowInfo = affectedByWorklist.iterator().next(); - affectedByWorklist.remove(currFlowInfo); - - if (currFlowInfo == flowInfo) { - result = true; - break; - } - - if (affectedBy.add(currFlowInfo)) { - affectedByWorklist.addAll(currFlowInfo.getAffectedBy()); - } - } - - isTransitivelyAffectedByCache.put(flowInfo, result); - return result; - } - - boolean markExposedAsArray(int dim) { - if (exposure >= dim) { - return false; - } - - exposure = dim; - return true; - } - - void markVisited() { - visited = true; - } - - boolean wasVisited() { - return visited; - } - - private void computeIndirectExposureCauses() { - // TODO(spoon): this only needs to consider immediate subtypes, not all - // subtypes - JClassType[] subtypes = baseType.getSubtypes(); - for (JClassType subtype : subtypes) { - JGenericType isGeneric = subtype.isGenericType(); - if (isGeneric == null) { - // Only generic types can cause a type parameter to be exposed - continue; - } - - // any problems should already have been captured by our caller, so we - // make a throw-away ProblemReport here. - if (!SerializableTypeOracleBuilder.shouldConsiderFieldsForSerialization( - subtype, typeFilter, new ProblemReport())) { - continue; - } - - JParameterizedType asParameterizationOf = subtype.asParameterizationOf(baseType); - Set paramsUsed = new LinkedHashSet(); - SerializableTypeOracleBuilder.recordTypeParametersIn( - asParameterizationOf.getTypeArgs()[ordinal], paramsUsed); - - for (JTypeParameter paramUsed : paramsUsed) { - recordCausesExposure(isGeneric, paramUsed.getOrdinal(), 0); - } - } - - JClassType type = baseType; - while (type != null) { - if (SerializableTypeOracleBuilder.shouldConsiderFieldsForSerialization( - type, typeFilter, new ProblemReport())) { - JField[] fields = type.getFields(); - for (JField field : fields) { - if (!SerializableTypeOracleBuilder.shouldConsiderForSerialization( - TreeLogger.NULL, true, field)) { - continue; - } - - JParameterizedType isParameterized = field.getType().getLeafType().isParameterized(); - if (isParameterized == null) { - continue; - } - - JClassType[] typeArgs = isParameterized.getTypeArgs(); - for (int i = 0; i < typeArgs.length; ++i) { - if (referencesTypeParameter(typeArgs[i], getTypeParameter())) { - JGenericType genericFieldType = isParameterized.getBaseType(); - recordCausesExposure(genericFieldType, i, 0); - JArrayType typeArgIsArray = typeArgs[i].isArray(); - if (typeArgIsArray != null - && typeArgIsArray.getLeafType() == getTypeParameter()) { - int dims = typeArgIsArray.getRank(); - recordCausesExposure(genericFieldType, i, dims); - } - } - } - } - } - - /* - * Counting on substitution to propagate the type parameter. - */ - type = type.getSuperclass(); - } - } - - private Collection getAffectedBy() { - return causesExposure.keySet(); - } - - /** - * The same as - * {@link TypeParameterExposureComputer#getFlowInfo(JGenericType, int)}, - * except that it additionally adds this as a listener to the - * returned flow info. - */ - private TypeParameterFlowInfo getFlowInfo(JGenericType type, int index) { - TypeParameterFlowInfo flowInfo = TypeParameterExposureComputer.this.getFlowInfo( - type, index); - flowInfo.addListener(this); - return flowInfo; - } - - private void recordCausesExposure(JGenericType type, int index, int level) { - assert (index < type.getTypeParameters().length); - TypeParameterFlowInfo flowInfo = getFlowInfo(type, index); - Integer oldLevel = causesExposure.get(flowInfo); - if (oldLevel == null || oldLevel < level) { - causesExposure.put(flowInfo, level); - } - } - - private boolean referencesTypeParameter(JClassType classType, - JTypeParameter typeParameter) { - Set typeParameters = new LinkedHashSet(); - SerializableTypeOracleBuilder.recordTypeParametersIn(classType, - typeParameters); - return typeParameters.contains(typeParameter); - } - } - - /** - * Type parameter is exposed. - */ - static final int EXPOSURE_DIRECT = 0; - - /** - * Type parameter is exposed as a bounded array. The value is the max bound of - * the exposure. - */ - static final int EXPOSURE_MIN_BOUNDED_ARRAY = EXPOSURE_DIRECT + 1; - - /** - * Type parameter is not exposed. - */ - static final int EXPOSURE_NONE = -1; - - private TypeFilter typeFilter; - - private final Map typeParameterToFlowInfo = new IdentityHashMap(); - - private final Set worklist = new LinkedHashSet(); - - TypeParameterExposureComputer(TypeFilter typeFilter) { - this.typeFilter = typeFilter; - } - - /** - * Computes flow information for the specified type parameter. If it has - * already been computed just return the value of the previous computation. - * - * @param type the generic type whose type parameter flow we are interested in - * @param index the index of the type parameter whose flow we want to compute - */ - public TypeParameterFlowInfo computeTypeParameterExposure(JGenericType type, - int index) { - // check if it has already been computed - JTypeParameter[] typeParameters = type.getTypeParameters(); - assert (index < typeParameters.length); - JTypeParameter typeParameter = typeParameters[index]; - TypeParameterFlowInfo queryFlow = typeParameterToFlowInfo.get(typeParameter); - if (queryFlow != null) { - return queryFlow; - } - - // not already computed; compute it - queryFlow = getFlowInfo(type, index); // adds it to the work list as a - // side effect - - while (!worklist.isEmpty()) { - TypeParameterFlowInfo info = worklist.iterator().next(); - worklist.remove(info); - - boolean didChange = info.updateFlowInfo(); - - if (didChange) { - for (TypeParameterFlowInfo listener : info.getListeners()) { - worklist.add(listener); - } - } - } - - return queryFlow; - } - - public void setTypeFilter(TypeFilter typeFilter) { - this.typeFilter = typeFilter; - } - - /** - * Return the parameter flow info for a type parameter specified by class and - * index. If the flow info did not previously exist, create it and add it to - * the work list. - */ - private TypeParameterFlowInfo getFlowInfo(JGenericType type, int index) { - JTypeParameter typeParameter = type.getTypeParameters()[index]; - TypeParameterFlowInfo info = typeParameterToFlowInfo.get(typeParameter); - if (info == null) { - info = new TypeParameterFlowInfo(type, index); - typeParameterToFlowInfo.put(typeParameter, info); - worklist.add(info); - } - return info; - } -} \ No newline at end of file diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/TypePaths.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/TypePaths.java deleted file mode 100755 index 87255721343..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/TypePaths.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright 2008 Google Inc. - * - * 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 de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc; - -import com.google.gwt.core.ext.typeinfo.JArrayType; -import com.google.gwt.core.ext.typeinfo.JClassType; -import com.google.gwt.core.ext.typeinfo.JField; -import com.google.gwt.core.ext.typeinfo.JGenericType; -import com.google.gwt.core.ext.typeinfo.JType; -import com.google.gwt.core.ext.typeinfo.JTypeParameter; - -/** - * Paths of types and utility methods for creating them. These are used by - * {@link SerializableTypeOracleBuilder} to record why it visits the types it - * does. - */ -class TypePaths { - /** - * A path of types. This interface does not currently expose the type itself, - * because these are currently only used for logging. - */ - interface TypePath { - /** - * Get the previous element on this type path, or null if - * this is a one-element path. - */ - TypePath getParent(); - - String toString(); - } - - static TypePaths.TypePath createArrayComponentPath( - final JArrayType arrayType, final TypePaths.TypePath parent) { - assert (arrayType != null); - - return new TypePaths.TypePath() { - public TypePaths.TypePath getParent() { - return parent; - } - - @Override - public String toString() { - return "Type '" - + arrayType.getComponentType().getParameterizedQualifiedSourceName() - + "' is reachable from array type '" - + arrayType.getParameterizedQualifiedSourceName() + "'"; - } - }; - } - - static TypePaths.TypePath createFieldPath(final TypePaths.TypePath parent, - final JField field) { - return new TypePaths.TypePath() { - public TypePaths.TypePath getParent() { - return parent; - } - - @Override - public String toString() { - JType type = field.getType(); - JClassType enclosingType = field.getEnclosingType(); - return "'" + type.getParameterizedQualifiedSourceName() - + "' is reachable from field '" + field.getName() + "' of type '" - + enclosingType.getParameterizedQualifiedSourceName() + "'"; - } - }; - } - - static TypePaths.TypePath createRootPath(final JType type) { - assert (type != null); - - return new TypePaths.TypePath() { - public TypePaths.TypePath getParent() { - return null; - } - - @Override - public String toString() { - return "Started from '" + type.getParameterizedQualifiedSourceName() - + "'"; - } - }; - } - - static TypePaths.TypePath createSubtypePath(final TypePaths.TypePath parent, - final JType type, final JClassType supertype) { - assert (type != null); - assert (supertype != null); - - return new TypePaths.TypePath() { - public TypePaths.TypePath getParent() { - return parent; - } - - @Override - public String toString() { - return "'" + type.getParameterizedQualifiedSourceName() - + "' is reachable as a subtype of type '" + supertype + "'"; - } - }; - } - - static TypePaths.TypePath createSupertypePath( - final TypePaths.TypePath parent, final JType type, - final JClassType subtype) { - assert (type != null); - assert (subtype != null); - - return new TypePaths.TypePath() { - public TypePaths.TypePath getParent() { - return parent; - } - - @Override - public String toString() { - return "'" + type.getParameterizedQualifiedSourceName() - + "' is reachable as a supertype of type '" + subtype + "'"; - } - }; - } - - static TypePaths.TypePath createTypeArgumentPath( - final TypePaths.TypePath parent, final JGenericType baseType, - final int typeArgIndex, final JClassType typeArg) { - assert (baseType != null); - assert (typeArg != null); - - return new TypePaths.TypePath() { - public TypePaths.TypePath getParent() { - return parent; - } - - @Override - public String toString() { - return "'" + typeArg.getParameterizedQualifiedSourceName() - + "' is reachable from type argument " + typeArgIndex - + " of type '" + baseType.getParameterizedQualifiedSourceName() - + "'"; - } - }; - } - - static TypePaths.TypePath createTypeParameterInRootPath( - final TypePaths.TypePath parent, final JTypeParameter typeParameter) { - assert (typeParameter != null); - - return new TypePaths.TypePath() { - public TypePaths.TypePath getParent() { - return parent; - } - - @Override - public String toString() { - String parameterString = typeParameter.getName(); - if (typeParameter.getDeclaringClass() != null) { - parameterString += " of class " - + typeParameter.getDeclaringClass().getQualifiedSourceName(); - } - return "'" - + typeParameter.getFirstBound().getParameterizedQualifiedSourceName() - + "' is reachable as an upper bound of type parameter " - + parameterString + ", which appears in a root type"; - } - }; - } -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/TypeSerializerCreator.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/TypeSerializerCreator.java deleted file mode 100755 index c5ed8580032..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/rebind/filter/serialization/com/google/gwt/user/rebind/rpc/TypeSerializerCreator.java +++ /dev/null @@ -1,560 +0,0 @@ -/* - * Copyright 2008 Google Inc. - * - * 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 de.csenk.gwt.ws.rebind.filter.serialization.com.google.gwt.user.rebind.rpc; - -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.google.gwt.core.client.JavaScriptObject; -import com.google.gwt.core.client.JsArrayString; -import com.google.gwt.core.ext.BadPropertyValueException; -import com.google.gwt.core.ext.ConfigurationProperty; -import com.google.gwt.core.ext.GeneratorContext; -import com.google.gwt.core.ext.TreeLogger; -import com.google.gwt.core.ext.UnableToCompleteException; -import com.google.gwt.core.ext.typeinfo.JClassType; -import com.google.gwt.core.ext.typeinfo.JMethod; -import com.google.gwt.core.ext.typeinfo.JParameterizedType; -import com.google.gwt.core.ext.typeinfo.JType; -import com.google.gwt.core.ext.typeinfo.TypeOracle; -import com.google.gwt.user.client.rpc.SerializationException; -import com.google.gwt.user.client.rpc.SerializationStreamReader; -import com.google.gwt.user.client.rpc.SerializationStreamWriter; -import com.google.gwt.user.client.rpc.impl.Serializer; -import com.google.gwt.user.client.rpc.impl.SerializerBase; -import com.google.gwt.user.rebind.ClassSourceFileComposerFactory; -import com.google.gwt.user.rebind.SourceWriter; - -/** - * This class generates a class with name 'typeSerializerClassName' that is able - * to serialize and deserialize a set of types into or out of a stream. The set - * of types is obtained from the SerializableTypeOracle object. - */ -public class TypeSerializerCreator { - - /** - * Configuration property to use type indices instead of type signatures. - */ - public static final String GWT_ELIDE_TYPE_NAMES_FROM_RPC = "gwt.elideTypeNamesFromRPC"; - - /** - * Default number of types to split createMethodMap entries into. Zero means - * no sharding occurs. Stored as a string since it is used as a default - * property value. - * - * Note that the inliner will likely reassemble the shards if it is used in - * web mode, but it isn't needed there anyway. - * - * TODO: remove this (and related code) when it is no longer needed. - */ - private static final String DEFAULT_CREATEMETHODMAP_SHARD_SIZE = "0"; - - /** - * Java system property name to override the above. - */ - private static final String GWT_CREATEMETHODMAP_SHARD_SIZE = "gwt.typecreator.shard.size"; - - private static int shardSize = -1; - - private static void computeShardSize(TreeLogger logger) - throws UnableToCompleteException { - String shardSizeProperty = System.getProperty( - GWT_CREATEMETHODMAP_SHARD_SIZE, DEFAULT_CREATEMETHODMAP_SHARD_SIZE); - try { - shardSize = Integer.valueOf(shardSizeProperty); - if (shardSize < 0) { - logger.log(TreeLogger.ERROR, GWT_CREATEMETHODMAP_SHARD_SIZE - + " must be non-negative: " + shardSizeProperty); - throw new UnableToCompleteException(); - } - } catch (NumberFormatException e) { - logger.log(TreeLogger.ERROR, "Property " + GWT_CREATEMETHODMAP_SHARD_SIZE - + " not a number: " + shardSizeProperty, e); - throw new UnableToCompleteException(); - } - } - - private final GeneratorContext context; - - private final SerializableTypeOracle deserializationOracle; - - private final boolean elideTypeNames; - - private final SerializableTypeOracle serializationOracle; - - private final JType[] serializableTypes; - - private final SourceWriter srcWriter; - - private final TypeOracle typeOracle; - - private final String typeSerializerClassName; - - private final Map typeStrings = new IdentityHashMap(); - - public TypeSerializerCreator(TreeLogger logger, - SerializableTypeOracle serializationOracle, - SerializableTypeOracle deserializationOracle, GeneratorContext context, - String typeSerializerClassName) throws UnableToCompleteException { - this.context = context; - this.typeSerializerClassName = typeSerializerClassName; - this.serializationOracle = serializationOracle; - this.deserializationOracle = deserializationOracle; - - this.typeOracle = context.getTypeOracle(); - - Set typesSet = new HashSet(); - typesSet.addAll(Arrays.asList(serializationOracle.getSerializableTypes())); - typesSet.addAll(Arrays.asList(deserializationOracle.getSerializableTypes())); - serializableTypes = typesSet.toArray(new JType[0]); - Arrays.sort(serializableTypes, - SerializableTypeOracleBuilder.JTYPE_COMPARATOR); - - srcWriter = getSourceWriter(logger, context); - if (shardSize < 0) { - computeShardSize(logger); - } - logger.log(TreeLogger.TRACE, "Using a shard size of " + shardSize - + " for TypeSerializerCreator createMethodMap"); - - try { - ConfigurationProperty prop - = context.getPropertyOracle().getConfigurationProperty( - GWT_ELIDE_TYPE_NAMES_FROM_RPC); - elideTypeNames = Boolean.parseBoolean(prop.getValues().get(0)); - } catch (BadPropertyValueException e) { - logger.log(TreeLogger.ERROR, "The configuration property " - + GWT_ELIDE_TYPE_NAMES_FROM_RPC - + " was not defined. Is RemoteService.gwt.xml inherited?"); - throw new UnableToCompleteException(); - } - } - - public Map getTypeStrings() { - return Collections.unmodifiableMap(typeStrings); - } - - public String realize(TreeLogger logger) throws UnableToCompleteException { - logger = logger.branch(TreeLogger.DEBUG, - "Generating TypeSerializer for service interface '" - + getTypeSerializerClassName() + "'", null); - String typeSerializerName = getTypeSerializerClassName(); - if (srcWriter == null) { - return typeSerializerName; - } - - createFieldSerializers(logger, context); - - writeStaticFields(); - - writeStaticInitializer(); - - writeCreateMethods(); - - writeRegisterSignatures(); - - writeRegisterMethods(); - - writeRaiseSerializationException(); - - srcWriter.commit(logger); - - return typeSerializerName; - } - - /* - * Create a field serializer for a type if it does not have a custom - * serializer. - */ - private void createFieldSerializer(TreeLogger logger, GeneratorContext ctx, - JType type) { - assert (type != null); - assert (serializationOracle.isSerializable(type) || deserializationOracle.isSerializable(type)); - - JParameterizedType parameterizedType = type.isParameterized(); - if (parameterizedType != null) { - createFieldSerializer(logger, ctx, parameterizedType.getRawType()); - return; - } - - JClassType customFieldSerializer = SerializableTypeOracleBuilder.findCustomFieldSerializer( - typeOracle, type); - if (customFieldSerializer != null) { - return; - } - - /* - * Only a JClassType can reach this point in the code. JPrimitives have been - * removed because their serialization is built in, interfaces have been - * removed because they are not an instantiable type and parameterized types - * have been broken down into their raw types. - */ - assert (type.isClass() != null || type.isArray() != null); - - FieldSerializerCreator creator = new FieldSerializerCreator(typeOracle, - serializationOracle, deserializationOracle, (JClassType) type); - creator.realize(logger, ctx); - } - - /* - * Create all of the necessary field serializers. - */ - private void createFieldSerializers(TreeLogger logger, GeneratorContext ctx) { - JType[] types = getSerializableTypes(); - int typeCount = types.length; - for (int typeIndex = 0; typeIndex < typeCount; ++typeIndex) { - JType type = types[typeIndex]; - assert (type != null); - - createFieldSerializer(logger, ctx, type); - } - } - - private String getCreateMethodName(JType type) { - assert (type.isArray() == null); - - return "create_" - + SerializationUtils.getFieldSerializerName(typeOracle, type).replace( - '.', '_'); - } - - private String[] getPackageAndClassName(String fullClassName) { - String className = fullClassName; - String packageName = ""; - int index = -1; - if ((index = className.lastIndexOf('.')) >= 0) { - packageName = className.substring(0, index); - className = className.substring(index + 1, className.length()); - } - return new String[] {packageName, className}; - } - - private JType[] getSerializableTypes() { - return serializableTypes; - } - - private SourceWriter getSourceWriter(TreeLogger logger, GeneratorContext ctx) { - String name[] = getPackageAndClassName(getTypeSerializerClassName()); - String packageName = name[0]; - String className = name[1]; - PrintWriter printWriter = ctx.tryCreate(logger, packageName, className); - if (printWriter == null) { - return null; - } - - ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory( - packageName, className); - - composerFactory.addImport(JavaScriptObject.class.getName()); - composerFactory.addImport(JsArrayString.class.getName()); - composerFactory.addImport(Serializer.class.getName()); - composerFactory.addImport(SerializationException.class.getName()); - composerFactory.addImport(SerializationStreamReader.class.getName()); - composerFactory.addImport(SerializationStreamWriter.class.getName()); - - composerFactory.setSuperclass(SerializerBase.class.getName()); - return composerFactory.createSourceWriter(ctx, printWriter); - } - - private String getTypeSerializerClassName() { - return typeSerializerClassName; - } - - /** - * @param type - * @return - */ - private String getTypeString(JType type) { - String typeString = type.getQualifiedBinaryName() + "/" - + SerializationUtils.getSerializationSignature(typeOracle, type); - return typeString; - } - - /** - * Return true if this type is concrete and has a custom field - * serializer that does not declare an instantiate method. - * - * @param type - * @return - */ - private boolean needsCreateMethod(JType type) { - // If this type is abstract it will not be serialized into the stream - // - if (!deserializationOracle.maybeInstantiated(type)) { - return false; - } - - if (type.isArray() != null) { - return false; - } - - JClassType customSerializer = SerializableTypeOracleBuilder.findCustomFieldSerializer( - typeOracle, type); - if (customSerializer == null) { - return false; - } - - JMethod customInstantiate = customSerializer.findMethod( - "instantiate", - new JType[] {typeOracle.findType(SerializationStreamReader.class.getName())}); - if (customInstantiate != null) { - return false; - } - - return true; - } - - private void writeCreateMethods() { - JType[] types = getSerializableTypes(); - for (int typeIndex = 0; typeIndex < types.length; ++typeIndex) { - JType type = types[typeIndex]; - assert (serializationOracle.isSerializable(type) || deserializationOracle.isSerializable(type)); - - if (!needsCreateMethod(type)) { - continue; - } - - /* - * Only classes with custom field serializers that do no declare - * instantiate methods get here - */ - srcWriter.print("private static native "); - srcWriter.print(type.getQualifiedSourceName()); - srcWriter.print(" "); - srcWriter.print(getCreateMethodName(type)); - srcWriter.println("(SerializationStreamReader streamReader) throws SerializationException /*-{"); - srcWriter.indent(); - srcWriter.print("return @"); - srcWriter.print(type.getQualifiedSourceName()); - srcWriter.println("::new()();"); - srcWriter.outdent(); - srcWriter.println("}-*/;"); - srcWriter.println(); - } - } - - private void writeRaiseSerializationException() { - srcWriter.println("private static void raiseSerializationException(String msg) throws SerializationException {"); - srcWriter.indentln("throw new SerializationException(msg);"); - srcWriter.println("}"); - srcWriter.println(); - } - - private void writeRegisterMethods() { - srcWriter.println("private static native void registerMethods() /*-{"); - srcWriter.indent(); - - List filteredTypes = new ArrayList(); - JType[] types = getSerializableTypes(); - int n = types.length; - for (int index = 0; index < n; ++index) { - JType type = types[index]; - if (serializationOracle.maybeInstantiated(type) - || deserializationOracle.maybeInstantiated(type)) { - filteredTypes.add(type); - } - } - - boolean shard = shardSize > 0 && filteredTypes.size() > shardSize; - int shardCount = 0; - - if (shard) { - srcWriter.println("(function() {"); - } - - for (JType type : filteredTypes) { - if (shard && ++shardCount % shardSize == 0) { - srcWriter.println("})();"); - srcWriter.println("(function() {"); - } - - srcWriter.println("@com.google.gwt.user.client.rpc.impl.SerializerBase" - + "::registerMethods(" - + "Lcom/google/gwt/user/client/rpc/impl/SerializerBase$MethodMap;" - + "Ljava/lang/String;" + "Lcom/google/gwt/core/client/JsArray;)("); - - srcWriter.indentln("@" + typeSerializerClassName + "::methodMap,"); - - String typeString = typeStrings.get(type); - assert typeString != null : "Missing type signature for " - + type.getQualifiedSourceName(); - srcWriter.indentln("\"" + typeString + "\" , ["); - - srcWriter.indent(); - writeTypeMethods(type); - srcWriter.outdent(); - - srcWriter.indentln("]);"); - srcWriter.println(); - } - - if (shard) { - srcWriter.println("})();"); - } - - srcWriter.outdent(); - srcWriter.println("}-*/;"); - srcWriter.println(); - } - - private void writeRegisterSignatures() { - srcWriter.println("private static native void registerSignatures() /*-{"); - srcWriter.indent(); - - int index = 0; - boolean shard = shardSize > 0 && getSerializableTypes().length > shardSize; - int shardCount = 0; - - if (shard) { - srcWriter.println("(function() {"); - } - - for (JType type : getSerializableTypes()) { - - String typeString; - if (elideTypeNames) { - typeString = Integer.toString(++index, Character.MAX_RADIX); - } else { - typeString = getTypeString(type); - } - typeStrings.put(type, typeString); - - if (!serializationOracle.maybeInstantiated(type) - && !deserializationOracle.maybeInstantiated(type)) { - continue; - } - - String jsniTypeRef; - jsniTypeRef = type.getLeafType().getQualifiedBinaryName(); - while (type.isArray() != null) { - jsniTypeRef += "[]"; - type = type.isArray().getComponentType(); - } - - if (shard && ++shardCount % shardSize == 0) { - srcWriter.println("})();"); - srcWriter.println("(function() {"); - } - - srcWriter.println("@com.google.gwt.user.client.rpc.impl.SerializerBase" - + "::registerSignature(" - + "Lcom/google/gwt/core/client/JsArrayString;" + "Ljava/lang/Class;" - + "Ljava/lang/String;)("); - srcWriter.indent(); - srcWriter.println("@" + typeSerializerClassName + "::signatureMap,"); - srcWriter.println("@" + jsniTypeRef + "::class,"); - srcWriter.println("\"" + typeString + "\");"); - srcWriter.outdent(); - srcWriter.println(); - } - - if (shard) { - srcWriter.println("})();"); - } - - srcWriter.outdent(); - srcWriter.println("}-*/;"); - srcWriter.println(); - } - - private void writeStaticFields() { - srcWriter.println("private static final MethodMap methodMap = JavaScriptObject.createObject().cast();"); - srcWriter.println("private static final JsArrayString signatureMap = JavaScriptObject.createArray().cast();"); - srcWriter.println("protected MethodMap getMethodMap() { return methodMap; }"); - srcWriter.println("protected JsArrayString getSignatureMap() { return signatureMap; }"); - srcWriter.println(); - } - - private void writeStaticInitializer() { - srcWriter.println("static {"); - srcWriter.indentln("registerMethods();"); - srcWriter.indentln("registerSignatures();"); - srcWriter.println("}"); - } - - /** - * Write an entry in the createMethodMap method for one type. - * - * @param type type to generate entry for - */ - private void writeTypeMethods(JType type) { - srcWriter.indent(); - String serializerName = SerializationUtils.getFieldSerializerName( - typeOracle, type); - - // First the initialization method - if (deserializationOracle.maybeInstantiated(type)) { - srcWriter.print("@"); - if (needsCreateMethod(type)) { - srcWriter.print(getTypeSerializerClassName()); - srcWriter.print("::"); - srcWriter.print(getCreateMethodName(type)); - } else { - srcWriter.print(serializerName); - srcWriter.print("::instantiate"); - } - srcWriter.print("(L" - + SerializationStreamReader.class.getName().replace('.', '/') + ";)"); - } - srcWriter.println(","); - - JClassType customSerializer = SerializableTypeOracleBuilder.findCustomFieldSerializer( - typeOracle, type); - - // Now the deserialization method - if (deserializationOracle.isSerializable(type)) { - // Assume param type is the concrete type of the serialized type. - JType paramType = type; - if (customSerializer != null) { - // But a custom serializer may specify a looser type. - JMethod deserializationMethod = CustomFieldSerializerValidator.getDeserializationMethod( - customSerializer, (JClassType) type); - paramType = deserializationMethod.getParameters()[1].getType(); - } - srcWriter.print("@" + serializerName); - srcWriter.print("::deserialize(L" - + SerializationStreamReader.class.getName().replace('.', '/') + ";" - + paramType.getJNISignature() + ")"); - } - srcWriter.println(","); - - // Now the serialization method - if (serializationOracle.isSerializable(type)) { - // Assume param type is the concrete type of the serialized type. - JType paramType = type; - if (customSerializer != null) { - // But a custom serializer may specify a looser type. - JMethod serializationMethod = CustomFieldSerializerValidator.getSerializationMethod( - customSerializer, (JClassType) type); - paramType = serializationMethod.getParameters()[1].getType(); - } - srcWriter.print("@" + serializerName); - srcWriter.print("::serialize(L" - + SerializationStreamWriter.class.getName().replace('.', '/') + ";" - + paramType.getJNISignature() + ")"); - srcWriter.println(); - } - srcWriter.outdent(); - } -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/server/filter/StatisticsFilter.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/server/filter/StatisticsFilter.java deleted file mode 100755 index cb03ef252f8..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/server/filter/StatisticsFilter.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.server.filter; - -import de.csenk.gwt.ws.shared.Connection; -import de.csenk.gwt.ws.shared.filter.DefaultFilter; - -/** - * @author senk.christian@googlemail.com - * @date 02.09.2010 - * @time 10:56:57 - * - */ -public class StatisticsFilter extends DefaultFilter { - - private long receivedByteCount; - private long sentByteCount; - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.shared.filter.FilterImpl#onMessageReceived(de.csenk.gwt.ws.shared.Filter.NextFilter, de.csenk.gwt.ws.shared.Connection, java.lang.Object) - */ - @Override - public void onMessageReceived(NextFilter nextFilter, Connection connection, - Object message) throws Throwable { - assert message instanceof String; - - String strMsg = (String) message; - int byteCount = strMsg.getBytes().length; - receivedByteCount += byteCount; - - //TODO gwtws: Use a logging facade - System.out.println("Received " + byteCount + " bytes and " + receivedByteCount + " in total"); - nextFilter.onMessageReceived(connection, message); - } - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.shared.filter.FilterImpl#onSend(de.csenk.gwt.ws.shared.Filter.NextFilter, de.csenk.gwt.ws.shared.Connection, java.lang.Object) - */ - @Override - public void onSend(NextFilter nextFilter, Connection connection, - Object message) throws Throwable { - assert message instanceof String; - - String strMsg = (String) message; - int byteCount = strMsg.getBytes().length; - sentByteCount += byteCount; - - //TODO gwtws: Use a logging facade - System.out.println("Sent " + byteCount + " bytes and " + sentByteCount + " in total"); - nextFilter.onSend(connection, message); - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/server/filter/serialization/ServerGWTSerializationFilter.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/server/filter/serialization/ServerGWTSerializationFilter.java deleted file mode 100755 index 161c5bad8e5..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/server/filter/serialization/ServerGWTSerializationFilter.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.server.filter.serialization; - -import com.google.gwt.user.server.rpc.SerializationPolicyProvider; - -import de.csenk.gwt.ws.client.filter.serialization.ClientGWTSerializationFilter; -import de.csenk.gwt.ws.shared.Connection; - -/** - * @author senk.christian@googlemail.com - * @date 01.09.2010 - * @time 17:38:04 - * - */ -public class ServerGWTSerializationFilter extends ClientGWTSerializationFilter { - - private ClassLoader contextClassLoader; - - /** - * @param serializationPolicyProvider - */ - public ServerGWTSerializationFilter(SerializationPolicyProvider serializationPolicyProvider) { - super(new ServerGWTSerializer(serializationPolicyProvider)); - } - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.client.filter.serialization.GWTClientSerializationFilter#onMessageReceived(de.csenk.gwt.ws.shared.Filter.NextFilter, de.csenk.gwt.ws.shared.Connection, java.lang.Object) - */ - @Override - public void onMessageReceived(NextFilter nextFilter, Connection connection, - Object message) throws Throwable { - assert message instanceof String; - - Object deserializedObject = null; - ClassLoader originalContextCL = Thread.currentThread().getContextClassLoader(); - try { - Thread.currentThread().setContextClassLoader(contextClassLoader); - deserializedObject = getSerializer().deserialize((String) message); - } finally { - Thread.currentThread().setContextClassLoader(originalContextCL); - } - - nextFilter.onMessageReceived(connection, deserializedObject); - } - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.shared.filter.FilterImpl#onConnectionOpened(de.csenk.gwt.ws.shared.Filter.NextFilter, de.csenk.gwt.ws.shared.Connection) - */ - @Override - public void onConnectionOpened(NextFilter nextFilter, Connection connection) - throws Throwable { - contextClassLoader = Thread.currentThread().getContextClassLoader(); - - super.onConnectionOpened(nextFilter, connection); - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/server/filter/serialization/ServerGWTSerializer.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/server/filter/serialization/ServerGWTSerializer.java deleted file mode 100755 index dfef6ee7dad..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/server/filter/serialization/ServerGWTSerializer.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.server.filter.serialization; - -import com.google.gwt.user.client.rpc.SerializationException; -import com.google.gwt.user.server.rpc.RPC; -import com.google.gwt.user.server.rpc.SerializationPolicy; -import com.google.gwt.user.server.rpc.SerializationPolicyProvider; -import com.google.gwt.user.server.rpc.impl.ServerSerializationStreamReader; -import com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter; - -import de.csenk.gwt.ws.shared.filter.serialization.GWTSerializer; - -/** - * @author senk.christian@googlemail.com - * @date 28.08.2010 - * @time 19:13:33 - * - */ -public class ServerGWTSerializer implements GWTSerializer { - - private SerializationPolicy serializationPolicy; - private final SerializationPolicyProvider serializationPolicyProvider; - - /** - * @param serializationPolicyProvider - */ - public ServerGWTSerializer(SerializationPolicyProvider serializationPolicyProvider) { - this.serializationPolicyProvider = serializationPolicyProvider; - } - - /* - * (non-Javadoc) - * - * @see - * de.csenk.gwt.ws.shared.filter.serialization.GWTSerializer#deserialize( - * java.lang.String) - */ - @Override - public Object deserialize(String serializedContent) - throws SerializationException { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - ServerSerializationStreamReader streamReader = new ServerSerializationStreamReader(classLoader, serializationPolicyProvider); - streamReader.prepareToRead(serializedContent); - - if (serializationPolicy == null) - serializationPolicy = streamReader.getSerializationPolicy(); - - String objClassName = maybeDeobfuscate(streamReader, streamReader.readString()); - try { - Class objClass = Class.forName(objClassName, false, classLoader); - return streamReader.deserializeValue(objClass); - } catch (ClassNotFoundException e) { - throw new SerializationException(e); - } - } - - /* - * (non-Javadoc) - * - * @see - * de.csenk.gwt.ws.shared.filter.serialization.GWTSerializer#serialize(java - * .lang.Object) - */ - @Override - public String serialize(Object obj) throws SerializationException { - SerializationPolicy policy = (serializationPolicy == null) ? RPC.getDefaultSerializationPolicy() : serializationPolicy; - - ServerSerializationStreamWriter streamWriter = new ServerSerializationStreamWriter(policy); - streamWriter.prepareToWrite(); - - streamWriter.writeString(obj.getClass().getName()); - streamWriter.serializeValue(obj, obj.getClass()); - - return streamWriter.toString(); - } - - /** - * Given a type identifier in the stream, attempt to deobfuscate it. Retuns - * the original identifier if deobfuscation is unnecessary or no mapping is - * known. - */ - private static String maybeDeobfuscate( - ServerSerializationStreamReader streamReader, String name) - throws SerializationException { - int index; - if ((index = name.indexOf('/')) != -1) { - return name.substring(0, index); - } - return name; - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/server/filter/serialization/ServletContextSerializationPolicyProvider.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/server/filter/serialization/ServletContextSerializationPolicyProvider.java deleted file mode 100755 index 00a97c7b1c1..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/server/filter/serialization/ServletContextSerializationPolicyProvider.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.server.filter.serialization; - -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.text.ParseException; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.ServletContext; - -import com.google.gwt.user.server.rpc.RPC; -import com.google.gwt.user.server.rpc.RemoteServiceServlet; -import com.google.gwt.user.server.rpc.SerializationPolicy; -import com.google.gwt.user.server.rpc.SerializationPolicyLoader; -import com.google.gwt.user.server.rpc.SerializationPolicyProvider; - -/** - * @author senk.christian@googlemail.com - * @date 01.09.2010 - * @time 21:24:40 - * - * Most of this code is copied from {@link RemoteServiceServlet}. - */ -public class ServletContextSerializationPolicyProvider implements - SerializationPolicyProvider { - - private final ServletContext servletContext; - - /** - * A cache of moduleBaseURL and serialization policy strong name to - * {@link SerializationPolicy}. - */ - private final Map serializationPolicyCache = new HashMap(); - - /** - * @param servletContext - */ - public ServletContextSerializationPolicyProvider( - ServletContext servletContext) { - this.servletContext = servletContext; - } - - /* - * (non-Javadoc) - * - * @seecom.google.gwt.user.server.rpc.SerializationPolicyProvider# - * getSerializationPolicy(java.lang.String, java.lang.String) - */ - @Override - public SerializationPolicy getSerializationPolicy(String moduleBaseURL, - String strongName) { - SerializationPolicy serializationPolicy = getCachedSerializationPolicy( - moduleBaseURL, strongName); - if (serializationPolicy != null) { - return serializationPolicy; - } - - serializationPolicy = doGetSerializationPolicy(moduleBaseURL, - strongName); - - if (serializationPolicy == null) { - // Failed to get the requested serialization policy; use the default - // log( - // "WARNING: Failed to get the SerializationPolicy '" - // + strongName - // + "' for module '" - // + moduleBaseURL - // + - // "'; a legacy, 1.3.3 compatible, serialization policy will be used. You may experience SerializationExceptions as a result.", - // null); - serializationPolicy = RPC.getDefaultSerializationPolicy(); - } - - // This could cache null or an actual instance. Either way we will not - // attempt to lookup the policy again. - putCachedSerializationPolicy(moduleBaseURL, strongName, - serializationPolicy); - - return serializationPolicy; - } - - /** - * @param moduleBaseURL - * @param strongName - * @param serializationPolicy - */ - private void putCachedSerializationPolicy(String moduleBaseURL, - String strongName, SerializationPolicy serializationPolicy) { - synchronized (serializationPolicyCache) { - serializationPolicyCache.put(moduleBaseURL + strongName, - serializationPolicy); - } - } - - /** - * @param moduleBaseURL - * @param strongName - * @return - */ - private SerializationPolicy getCachedSerializationPolicy( - String moduleBaseURL, String strongName) { - synchronized (serializationPolicyCache) { - return serializationPolicyCache.get(moduleBaseURL + strongName); - } - } - - /** - * @param moduleBaseURL - * @param strongName - * @return - */ - private SerializationPolicy doGetSerializationPolicy(String moduleBaseURL, - String strongName) { - // The request can tell you the path of the web app relative to the - // container root. - String contextPath = servletContext.getContextPath(); - - String modulePath = null; - if (moduleBaseURL != null) { - try { - modulePath = new URL(moduleBaseURL).getPath(); - } catch (MalformedURLException ex) { - // log the information, we will default - servletContext.log("Malformed moduleBaseURL: " + moduleBaseURL, - ex); - } - } - - SerializationPolicy serializationPolicy = null; - - /* - * Check that the module path must be in the same web app as the servlet - * itself. If you need to implement a scheme different than this, - * override this method. - */ - if (modulePath == null || !modulePath.startsWith(contextPath)) { - String message = "ERROR: The module path requested, " - + modulePath - + ", is not in the same web application as this servlet, " - + contextPath - + ". Your module may not be properly configured or your client and server code maybe out of date."; - servletContext.log(message, null); - } else { - // Strip off the context path from the module base URL. It should be - // a - // strict prefix. - String contextRelativePath = modulePath.substring(contextPath - .length()); - - String serializationPolicyFilePath = SerializationPolicyLoader - .getSerializationPolicyFileName(contextRelativePath - + strongName); - - // Open the RPC resource file and read its contents. - InputStream is = servletContext - .getResourceAsStream(serializationPolicyFilePath); - try { - if (is != null) { - try { - serializationPolicy = SerializationPolicyLoader - .loadFromStream(is, null); - } catch (ParseException e) { - servletContext.log( - "ERROR: Failed to parse the policy file '" - + serializationPolicyFilePath + "'", e); - } catch (IOException e) { - servletContext.log( - "ERROR: Could not read the policy file '" - + serializationPolicyFilePath + "'", e); - } - } else { - String message = "ERROR: The serialization policy file '" - + serializationPolicyFilePath - + "' was not found; did you forget to include it in this deployment?"; - servletContext.log(message); - } - } finally { - if (is != null) { - try { - is.close(); - } catch (IOException e) { - // Ignore this error - } - } - } - } - - return serializationPolicy; - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/server/handler/ServerMessageDispatchingHandler.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/server/handler/ServerMessageDispatchingHandler.java deleted file mode 100755 index e1715209cd5..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/server/handler/ServerMessageDispatchingHandler.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.server.handler; - -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import de.csenk.gwt.ws.shared.handler.DefaultMessageDispatchingHandler; - -/** - * @author senk.christian@googlemail.com - * @date 09.09.2010 - * @time 21:36:29 - * - */ -public class ServerMessageDispatchingHandler extends - DefaultMessageDispatchingHandler { - - /** - * @param handlers - * @param type - * @param object - * @return - */ - @SuppressWarnings("rawtypes") - protected synchronized Object findHandler(Map handlers, Class type, Set triedTypes) { - if (handlers == null || type == null) - return null; - - if (triedTypes != null && triedTypes.contains(type)) - return null; - - if (handlers.containsKey(type)) - return handlers.get(type); - - if (triedTypes == null) - triedTypes = new HashSet(); - - triedTypes.add(type); - - Class[] interfaces = type.getInterfaces(); - for (Class intf : interfaces) { - Object handler = findHandler(handlers, intf, triedTypes); - if (handler != null) - return handler; - } - - Class superClass = type.getSuperclass(); - return findHandler(handlers, superClass, null); - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/server/jetty/JettyWebSocketConnection.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/server/jetty/JettyWebSocketConnection.java deleted file mode 100755 index dea7e2d3678..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/server/jetty/JettyWebSocketConnection.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.server.jetty; - -import java.io.IOException; - -import org.eclipse.jetty.websocket.api.Session; -import org.eclipse.jetty.websocket.api.WebSocketAdapter; - -import de.csenk.gwt.ws.shared.Connection; -import de.csenk.gwt.ws.shared.FilterChain; -import de.csenk.gwt.ws.shared.Handler; -import de.csenk.gwt.ws.shared.Sender; -import de.csenk.gwt.ws.shared.filter.DefaultFilterChain; - -/** - * @author senk.christian@googlemail.com - * @date 25.08.2010 - * @time 13:56:30 - * - */ -public class JettyWebSocketConnection extends WebSocketAdapter implements Connection { - - private final Handler handler; - - private Session session; - private Sender sender; - - private final FilterChain filterChain; - - /** - * @param handler - */ - public JettyWebSocketConnection(final Handler handler) { - this.handler = handler; - this.filterChain = new DefaultFilterChain(this); - } - - @Override - public void onWebSocketBinary(byte[] payload, int offset, int len) { - filterChain.fireMessageReceived(new String(payload, offset, len)); - } - - @Override - public void onWebSocketClose(int statusCode, String reason) { - filterChain.fireConnectionClosed(); - } - - @Override - public void onWebSocketConnect(Session session) { - this.session = session; - sender = new OutboundSender(session); - filterChain.fireConnectionOpened(); - } - - @Override - public void onWebSocketText(String message) { - filterChain.fireMessageReceived(message); - } - - /* - * (non-Javadoc) - * - * @see de.csenk.gwt.ws.shared.Connection#close() - */ - @Override - public void close() { - try { - session.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - /* - * (non-Javadoc) - * - * @see de.csenk.gwt.ws.shared.Connection#getFilterChain() - */ - @Override - public FilterChain getFilterChain() { - return filterChain; - } - - /* - * (non-Javadoc) - * - * @see de.csenk.gwt.ws.shared.Connection#getHandler() - */ - @Override - public Handler getHandler() { - return handler; - } - - /* - * (non-Javadoc) - * - * @see de.csenk.gwt.ws.shared.Connection#getSender() - */ - @Override - public Sender getSender() { - return sender; - } - - /* - * (non-Javadoc) - * - * @see de.csenk.gwt.ws.shared.Connection#send(java.lang.Object) - */ - @Override - public void send(Object message) { - filterChain.fireSend(message); - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/server/jetty/OutboundSender.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/server/jetty/OutboundSender.java deleted file mode 100755 index c60d3c267b1..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/server/jetty/OutboundSender.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.server.jetty; - -import java.io.IOException; - -import org.eclipse.jetty.websocket.api.RemoteEndpoint; -import org.eclipse.jetty.websocket.api.Session; - -import de.csenk.gwt.ws.shared.Sender; - -/** - * @author senk.christian@googlemail.com - * @date 30.08.2010 - * @time 15:46:16 - * - */ -public class OutboundSender implements Sender { - - private final RemoteEndpoint outbound; - - public OutboundSender(Session session) { - this.outbound = session.getRemote(); - } - - /* - * (non-Javadoc) - * - * @see de.csenk.gwt.ws.shared.Sender#send(java.lang.String) - */ - @Override - public void send(String message) throws IOException { - outbound.sendString(message); - } -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/Connection.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/Connection.java deleted file mode 100755 index bfadea0b40d..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/Connection.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.shared; - -/** - * @author senk.christian@googlemail.com - * @date 26.08.2010 - * @time 13:06:59 - * - */ -public interface Connection { - - /** - * Sends a message through this {@link Connection}. - * - * @param message - */ - void send(Object message); - - /** - * Closes this {@link Connection}. - */ - void close(); - - /** - * @return - */ - Handler getHandler(); - - /** - * @return - */ - FilterChain getFilterChain(); - - /** - * @return - */ - Sender getSender(); -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/ExceptionHandler.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/ExceptionHandler.java deleted file mode 100755 index c216696681a..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/ExceptionHandler.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.shared; - -/** - * @author senk.christian@googlemail.com - * @date 07.09.2010 - * @time 20:42:30 - * - */ -public interface ExceptionHandler { - - /** - * @param connection - * @param message - */ - void handleException(Connection connection, E exception); - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/Filter.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/Filter.java deleted file mode 100755 index 58ecb386e27..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/Filter.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.shared; - -/** - * @author senk.christian@googlemail.com - * @date 29.08.2010 - * @time 22:43:06 - * - */ -public interface Filter { - - /** - * @param connection - */ - void onConnectionOpened(NextFilter nextFilter, Connection connection) - throws Throwable; - - /** - * @param connection - */ - void onConnectionClosed(NextFilter nextFilter, Connection connection) - throws Throwable; - - /** - * @param caught - */ - void onExceptionCaught(NextFilter nextFilter, Connection connection, Throwable caught); - - /** - * @param connection - * @param message - */ - void onMessageReceived(NextFilter nextFilter, Connection connection, - Object message) throws Throwable; - - /** - * @param nextFilter - * @param connection - * @param message - * @throws Exception - */ - void onSend(NextFilter nextFilter, Connection connection, - Object message) throws Throwable; - - /** - * @author senk.christian@googlemail.com - * @date 30.08.2010 - * @time 10:49:48 - * - */ - public interface NextFilter { - - /** - * @param connection - */ - void onConnectionOpened(Connection connection) throws Throwable; - - /** - * @param connection - */ - void onConnectionClosed(Connection connection) throws Throwable; - - /** - * @param caught - */ - void onExceptionCaught(Connection connection, Throwable caught); - - /** - * @param connection - * @param message - */ - void onMessageReceived(Connection connection, Object message) - throws Throwable; - - /** - * @param connection - * @param message - * @throws Exception - */ - void onSend(Connection connection, Object message) - throws Throwable; - - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/FilterChain.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/FilterChain.java deleted file mode 100755 index 7061374bc36..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/FilterChain.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.shared; - -import de.csenk.gwt.ws.shared.Filter.NextFilter; - -/** - * @author senk.christian@googlemail.com - * @date 26.08.2010 - * @time 14:08:49 - * - */ -public interface FilterChain { - - /** - * @param filterName - * @param filter - */ - void addLast(String filterName, Filter filter); - - /** - * @param message - */ - void fireSend(Object message); - - /** - * - */ - void fireConnectionOpened(); - - - /** - * - */ - void fireConnectionClosed(); - - /** - * @param caught - */ - void fireExceptionCaught(Throwable caught); - - /** - * @param message - */ - void fireMessageReceived(Object message); - - /** - * @author senk.christian@googlemail.com - * @date 30.08.2010 - * @time 10:45:11 - * - */ - public interface Entry { - - /** - * @return - */ - String getName(); - - /** - * @return - */ - Filter getFilter(); - - /** - * @return - */ - NextFilter getNextFilter(); - - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/Handler.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/Handler.java deleted file mode 100755 index 1ea23cb4374..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/Handler.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.shared; - -/** - * @author senk.christian@googlemail.com - * @date 26.08.2010 - * @time 13:42:05 - * - */ -public interface Handler { - - /** - * @param connection - * @throws Throwable TODO - */ - void onConnectionOpened(Connection connection) throws Throwable; - - /** - * @param connection - * @throws Throwable TODO - */ - void onConnectionClosed(Connection connection) throws Throwable; - - /** - * @param caught - */ - void onExceptionCaught(Connection connection, Throwable caught); - - /** - * @param connection - * @param message - * @throws Throwable TODO - */ - void onMessageReceived(Connection connection, Object message) throws Throwable; - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/MessageDispatchingHandler.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/MessageDispatchingHandler.java deleted file mode 100755 index 289a067aa67..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/MessageDispatchingHandler.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.shared; - -/** - * @author senk.christian@googlemail.com - * @date 07.09.2010 - * @time 20:45:46 - * - */ -public interface MessageDispatchingHandler extends Handler { - - /** - * @param - * @param clazz - * @param handler - */ - void addReceivedMessageHandler(Class clazz, MessageHandler handler); - - /** - * @param - * @param clazz - * @param handler - */ - void addExceptionHandler(Class clazz, ExceptionHandler handler); - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/MessageHandler.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/MessageHandler.java deleted file mode 100755 index 1ed48a9e7de..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/MessageHandler.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.shared; - -/** - * @author senk.christian@googlemail.com - * @date 07.09.2010 - * @time 20:42:30 - * - */ -public interface MessageHandler { - - /** - * @param connection - * @param message - */ - void handleMessage(Connection connection, E message); - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/Sender.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/Sender.java deleted file mode 100755 index 6170d9a5d21..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/Sender.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.shared; - -import java.io.IOException; - -/** - * @author senk.christian@googlemail.com - * @date 30.08.2010 - * @time 16:01:11 - * - */ -public interface Sender { - - /** - * Sends a message over a web socket. - * - * @param message - */ - void send(String message) throws IOException; - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/DefaultFilter.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/DefaultFilter.java deleted file mode 100755 index 6cb414167b7..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/DefaultFilter.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.shared.filter; - -import de.csenk.gwt.ws.shared.Connection; -import de.csenk.gwt.ws.shared.Filter; - -/** - * @author senk.christian@googlemail.com - * @date 31.08.2010 - * @time 15:41:34 - * - */ -public class DefaultFilter implements Filter { - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.shared.Filter#onConnectionClosed(de.csenk.gwt.ws.shared.Filter.NextFilter, de.csenk.gwt.ws.shared.Connection) - */ - @Override - public void onConnectionClosed(NextFilter nextFilter, Connection connection) - throws Throwable { - nextFilter.onConnectionClosed(connection); - } - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.shared.Filter#onConnectionOpened(de.csenk.gwt.ws.shared.Filter.NextFilter, de.csenk.gwt.ws.shared.Connection) - */ - @Override - public void onConnectionOpened(NextFilter nextFilter, Connection connection) - throws Throwable { - nextFilter.onConnectionOpened(connection); - } - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.shared.Filter#onExceptionCaught(de.csenk.gwt.ws.shared.Filter.NextFilter, java.lang.Throwable) - */ - @Override - public void onExceptionCaught(NextFilter nextFilter, Connection connection, Throwable caught) { - nextFilter.onExceptionCaught(connection, caught); - } - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.shared.Filter#onMessageReceived(de.csenk.gwt.ws.shared.Filter.NextFilter, de.csenk.gwt.ws.shared.Connection, java.lang.Object) - */ - @Override - public void onMessageReceived(NextFilter nextFilter, Connection connection, - Object message) throws Throwable { - nextFilter.onMessageReceived(connection, message); - } - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.shared.Filter#onSendMessage(de.csenk.gwt.ws.shared.Filter.NextFilter, de.csenk.gwt.ws.shared.Connection, java.lang.Object) - */ - @Override - public void onSend(NextFilter nextFilter, Connection connection, - Object message) throws Throwable { - nextFilter.onSend(connection, message); - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/DefaultFilterChain.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/DefaultFilterChain.java deleted file mode 100755 index e7168410d98..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/DefaultFilterChain.java +++ /dev/null @@ -1,343 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.shared.filter; - -import java.util.HashMap; -import java.util.Map; - -import de.csenk.gwt.ws.shared.Connection; -import de.csenk.gwt.ws.shared.Filter; -import de.csenk.gwt.ws.shared.FilterChain; -import de.csenk.gwt.ws.shared.Filter.NextFilter; - -/** - * @author senk.christian@googlemail.com - * @date 30.08.2010 - * @time 16:12:24 - * - */ -public class DefaultFilterChain implements FilterChain { - - private final Map filterMap = new HashMap(); - - private final Connection connection; - - private final EntryImpl tailEntry; - private final EntryImpl headEntry; - - public DefaultFilterChain(Connection connection) { - this.connection = connection; - - tailEntry = new EntryImpl(TailFilter.NAME, new TailFilter(), null, null); - headEntry = new EntryImpl(HeadFilter.NAME, new HeadFilter(), null, - tailEntry); - tailEntry.prevEntry = headEntry; - } - - /* - * (non-Javadoc) - * - * @see de.csenk.gwt.ws.shared.FilterChain#addLast(java.lang.String, - * de.csenk.gwt.ws.shared.Filter) - */ - @Override - public synchronized void addLast(String filterName, Filter filter) { - checkNameIsNotReserved(filterName); - - EntryImpl filterEntry = insertFilter(tailEntry.prevEntry, filterName, filter); - filterMap.put(filterName, filterEntry); - } - - /** - * @param filterName - */ - private void checkNameIsNotReserved(String filterName) { - if (filterMap.containsKey(filterName)) - throw new IllegalStateException("There is already a filter with name '" + filterName + "'"); - } - - /** - * @param prevEntry - * @param name - * @param filter - */ - private synchronized EntryImpl insertFilter(EntryImpl prevEntry, String name, Filter filter) { - EntryImpl nextEntry = prevEntry.nextEntry; - EntryImpl newEntry = new EntryImpl(name, filter, prevEntry, nextEntry); - - prevEntry.nextEntry = newEntry; - nextEntry.prevEntry = newEntry; - - return newEntry; - } - - /* - * (non-Javadoc) - * - * @see - * de.csenk.gwt.ws.shared.FilterChain#fireSendMessage(de.csenk.gwt.ws.shared - * .Connection, java.lang.Object) - */ - @Override - public synchronized void fireSend(Object message) { - callPreviousSend(tailEntry, message); - } - - /** - * @param filterEntry - * @param connection - * @param message - */ - private void callPreviousSend(Entry filterEntry, Object message) { - if (filterEntry == null) - return; - - try { - Filter filter = filterEntry.getFilter(); - NextFilter nextFilter = filterEntry.getNextFilter(); - - filter.onSend(nextFilter, connection, message); - } catch (Throwable e) { - fireExceptionCaught(e); - } - } - - /* - * (non-Javadoc) - * - * @see - * de.csenk.gwt.ws.shared.FilterChain#fireExceptionCaught(de.csenk.gwt.ws. - * shared.Connection, java.lang.Throwable) - */ - @Override - public synchronized void fireExceptionCaught(Throwable caught) { - callNextExceptionCaught(headEntry, caught); - } - - /** - * @param filterEntry - * @param connection - * @param message - */ - private void callNextExceptionCaught(Entry filterEntry, Throwable caught) { - if (filterEntry == null) - return; - - try { - Filter filter = filterEntry.getFilter(); - NextFilter nextFilter = filterEntry.getNextFilter(); - - filter.onExceptionCaught(nextFilter, connection, caught); - } catch (Throwable e) { - fireExceptionCaught(e); - } - } - - /* - * (non-Javadoc) - * - * @see - * de.csenk.gwt.ws.shared.FilterChain#fireConnectionClosed(de.csenk.gwt.ws - * .shared.Connection) - */ - @Override - public synchronized void fireConnectionClosed() { - callNextConnectionClosed(headEntry); - } - - /** - * @param filterEntry - * @param connection - * @param message - */ - private void callNextConnectionClosed(Entry filterEntry) { - if (filterEntry == null) - return; - - try { - Filter filter = filterEntry.getFilter(); - NextFilter nextFilter = filterEntry.getNextFilter(); - - filter.onConnectionClosed(nextFilter, connection); - } catch (Throwable e) { - fireExceptionCaught(e); - } - } - - /* - * (non-Javadoc) - * - * @see - * de.csenk.gwt.ws.shared.FilterChain#fireConnectionOpened(de.csenk.gwt.ws - * .shared.Connection) - */ - @Override - public synchronized void fireConnectionOpened() { - callNextConnectionOpened(headEntry); - } - - /** - * @param filterEntry - * @param connection - * @param message - */ - private void callNextConnectionOpened(Entry filterEntry) { - if (filterEntry == null) - return; - - try { - Filter filter = filterEntry.getFilter(); - NextFilter nextFilter = filterEntry.getNextFilter(); - - filter.onConnectionOpened(nextFilter, connection); - } catch (Throwable e) { - fireExceptionCaught(e); - } - } - - /* - * (non-Javadoc) - * - * @see - * de.csenk.gwt.ws.shared.FilterChain#fireMessageReceived(de.csenk.gwt.ws. - * shared.Connection, java.lang.Object) - */ - @Override - public synchronized void fireMessageReceived(Object message) { - callNextMessageReceived(headEntry, message); - } - - /** - * @param filterEntry - * @param connection - * @param message - */ - private void callNextMessageReceived(Entry filterEntry, Object message) { - if (filterEntry == null) - return; - - try { - Filter filter = filterEntry.getFilter(); - NextFilter nextFilter = filterEntry.getNextFilter(); - - filter.onMessageReceived(nextFilter, connection, message); - } catch (Throwable e) { - fireExceptionCaught(e); - } - } - - /** - * @author senk.christian@googlemail.com - * @date 30.08.2010 - * @time 10:50:20 - * - */ - private class EntryImpl implements Entry { - - private final String name; - private final Filter filter; - private final NextFilter nextFilter; - - private EntryImpl prevEntry; - private EntryImpl nextEntry; - - /** - * @param name - * @param filter - * @param prevEntry - * @param nextEntry - */ - public EntryImpl(String name, Filter filter, EntryImpl prevEntry, - EntryImpl nextEntry) { - this.name = name; - this.filter = filter; - this.prevEntry = prevEntry; - this.nextEntry = nextEntry; - - this.nextFilter = createNextFilter(); - } - - /* - * (non-Javadoc) - * - * @see de.csenk.gwt.ws.shared.FilterChain.Entry#getFilter() - */ - @Override - public Filter getFilter() { - return filter; - } - - /* - * (non-Javadoc) - * - * @see de.csenk.gwt.ws.shared.FilterChain.Entry#getName() - */ - @Override - public String getName() { - return name; - } - - /* - * (non-Javadoc) - * - * @see de.csenk.gwt.ws.shared.FilterChain.Entry#getNextFilter() - */ - @Override - public NextFilter getNextFilter() { - return nextFilter; - } - - /** - * @return - */ - private NextFilter createNextFilter() { - return new NextFilter() { - - @Override - public void onSend(Connection connection, Object message) - throws Exception { - callPreviousSend(prevEntry, message); - } - - @Override - public void onMessageReceived(Connection connection, - Object message) throws Exception { - callNextMessageReceived(nextEntry, message); - } - - @Override - public void onExceptionCaught(Connection connection, Throwable caught) { - callNextExceptionCaught(nextEntry, caught); - } - - @Override - public void onConnectionOpened(Connection connection) - throws Exception { - callNextConnectionOpened(nextEntry); - } - - @Override - public void onConnectionClosed(Connection connection) - throws Exception { - callNextConnectionClosed(nextEntry); - } - - }; - } - - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/HeadFilter.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/HeadFilter.java deleted file mode 100755 index 0d8a9d6872b..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/HeadFilter.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.shared.filter; - -import de.csenk.gwt.ws.shared.Connection; -import de.csenk.gwt.ws.shared.Sender; - -/** - * @author senk.christian@googlemail.com - * @date 30.08.2010 - * @time 11:16:41 - * - */ -final class HeadFilter extends DefaultFilter { - - public static final String NAME = "head"; - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.shared.Filter#onSendMessage(de.csenk.gwt.ws.shared.Filter.NextFilter, de.csenk.gwt.ws.shared.Connection, java.lang.Object) - */ - @Override - public void onSend(NextFilter nextFilter, Connection connection, - Object message) throws Exception { - assert message instanceof String; - - Sender sender = connection.getSender(); - sender.send((String) message); - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/TailFilter.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/TailFilter.java deleted file mode 100755 index 98f62c4fec2..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/TailFilter.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.shared.filter; - -import de.csenk.gwt.ws.shared.Connection; - -/** - * @author senk.christian@googlemail.com - * @date 30.08.2010 - * @time 11:17:13 - * - */ -final class TailFilter extends DefaultFilter { - - public static final String NAME = "tail"; - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.shared.Filter#onConnectionClosed(de.csenk.gwt.ws.shared.Filter.NextFilter, de.csenk.gwt.ws.shared.Connection) - */ - @Override - public void onConnectionClosed(NextFilter nextFilter, Connection connection) - throws Throwable { - connection.getHandler().onConnectionClosed(connection); - } - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.shared.Filter#onConnectionOpened(de.csenk.gwt.ws.shared.Filter.NextFilter, de.csenk.gwt.ws.shared.Connection) - */ - @Override - public void onConnectionOpened(NextFilter nextFilter, Connection connection) - throws Throwable { - connection.getHandler().onConnectionOpened(connection); - } - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.shared.filter.FilterImpl#onExceptionCaught(de.csenk.gwt.ws.shared.Filter.NextFilter, de.csenk.gwt.ws.shared.Connection, java.lang.Throwable) - */ - @Override - public void onExceptionCaught(NextFilter nextFilter, Connection connection, - Throwable caught) { - connection.getHandler().onExceptionCaught(connection, caught); - } - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.shared.filter.FilterImpl#onMessageReceived(de.csenk.gwt.ws.shared.Filter.NextFilter, de.csenk.gwt.ws.shared.Connection, java.lang.Object) - */ - @Override - public void onMessageReceived(NextFilter nextFilter, Connection connection, - Object message) throws Throwable { - connection.getHandler().onMessageReceived(connection, message); - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/requestresponse/RequestMessage.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/requestresponse/RequestMessage.java deleted file mode 100755 index 4784cb0cb1d..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/requestresponse/RequestMessage.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * 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, either version 3 of the License, or - * (at your option) any later version. - * - * 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. If not, see . - */ - -package de.csenk.gwt.ws.shared.filter.requestresponse; - -import java.io.Serializable; - -/** - * @author Christian - * @date 10.10.2010 - * @time 12:40:21 - * - */ -@SuppressWarnings("serial") -public abstract class RequestMessage implements Serializable { - - private Integer requestID; - - private transient ResponseCallback responseCallback; - - /** - * @param responseCallback - */ - public RequestMessage(ResponseCallback responseCallback) { - this.responseCallback = responseCallback; - } - - /** - * @param requestID - */ - void setRequestID(Integer requestID) { - this.requestID = requestID; - } - - /** - * @return - */ - public Integer getRequestID() { - return requestID; - } - - /** - * @return - */ - public ResponseCallback getResponseCallback() { - return responseCallback; - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/requestresponse/RequestResponseFilter.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/requestresponse/RequestResponseFilter.java deleted file mode 100755 index 8770b7a37e1..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/requestresponse/RequestResponseFilter.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * 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, either version 3 of the License, or - * (at your option) any later version. - * - * 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. If not, see . - */ - -package de.csenk.gwt.ws.shared.filter.requestresponse; - -import java.util.HashMap; -import java.util.Map; - -import de.csenk.gwt.ws.shared.Connection; -import de.csenk.gwt.ws.shared.filter.DefaultFilter; - -/** - * @author Christian - * @date 10.10.2010 - * @time 13:04:24 - * - */ -public class RequestResponseFilter extends DefaultFilter { - - private int requestCounter = Integer.MIN_VALUE; - private final Map> requestMap = new HashMap>(); - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.shared.Filter#onMessageReceived(de.csenk.gwt.ws.shared.Filter.NextFilter, de.csenk.gwt.ws.shared.Connection, java.lang.Object) - */ - @Override - @SuppressWarnings("unchecked") - public void onMessageReceived(NextFilter nextFilter, Connection connection, - Object message) throws Throwable { - if (!(message instanceof ResponseMessage)) - nextFilter.onMessageReceived(connection, message); - - ResponseMessage responseMessage = (ResponseMessage) message; - if (responseMessage.getRequestID() != null) { - if (requestMap.containsKey(responseMessage.getRequestID())) { - ResponseCallback callback = (ResponseCallback) requestMap.get(responseMessage.getRequestID()); - requestMap.remove(responseMessage.getRequestID()); - - if (callback != null) - callback.onMessage(responseMessage); - } - } - } - - /* (non-Javadoc) - * @see de.csenk.gwt.ws.shared.Filter#onSend(de.csenk.gwt.ws.shared.Filter.NextFilter, de.csenk.gwt.ws.shared.Connection, java.lang.Object) - */ - @Override - public void onSend(NextFilter nextFilter, Connection connection, - Object message) throws Throwable { - if (!(message instanceof RequestMessage)) - nextFilter.onSend(connection, message); - - RequestMessage requestMessage = (RequestMessage) message; - if (requestMessage.getResponseCallback() != null) { - requestMessage.setRequestID(generateRequestID()); - - requestMap.put(requestMessage.getRequestID(), requestMessage.getResponseCallback()); - } - - nextFilter.onSend(connection, requestMessage); - } - - /** - * @return - */ - private int generateRequestID() { - if (requestCounter >= Integer.MAX_VALUE) { - requestCounter = Integer.MIN_VALUE; - return requestCounter; - } - - return requestCounter++; - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/requestresponse/ResponseCallback.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/requestresponse/ResponseCallback.java deleted file mode 100755 index 2e20768ddc0..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/requestresponse/ResponseCallback.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * 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, either version 3 of the License, or - * (at your option) any later version. - * - * 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. If not, see . - */ - -package de.csenk.gwt.ws.shared.filter.requestresponse; - -/** - * @author Christian - * @date 10.10.2010 - * @time 12:38:31 - * - */ -public interface ResponseCallback { - - void onMessage(T message); - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/requestresponse/ResponseMessage.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/requestresponse/ResponseMessage.java deleted file mode 100755 index 5b4aa97df46..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/requestresponse/ResponseMessage.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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, either version 3 of the License, or - * (at your option) any later version. - * - * 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. If not, see . - */ - -package de.csenk.gwt.ws.shared.filter.requestresponse; - -import java.io.Serializable; - -/** - * @author Christian - * @date 10.10.2010 - * @time 13:37:39 - * - */ -@SuppressWarnings("serial") -public abstract class ResponseMessage implements Serializable { - - private Integer requestID; - - /** - * @param requestID - */ - public ResponseMessage(Integer requestID) { - this.requestID = requestID; - } - - /** - * @return the requestID - */ - public Integer getRequestID() { - return requestID; - } - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/serialization/GWTSerializer.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/serialization/GWTSerializer.java deleted file mode 100755 index 1ca33c85477..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/serialization/GWTSerializer.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.shared.filter.serialization; - -import com.google.gwt.user.client.rpc.SerializationException; - -/** - * @author senk.christian@googlemail.com - * @date 27.08.2010 - * @time 14:20:14 - * - */ -public interface GWTSerializer { - - /** - * @param serializedContent - * @return - */ - Object deserialize(String serializedContent) throws SerializationException; - - /** - * @param obj - * @return - */ - String serialize(Object obj) throws SerializationException; - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/serialization/Serializable.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/serialization/Serializable.java deleted file mode 100755 index abf39d9ab54..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/filter/serialization/Serializable.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.shared.filter.serialization; - -/** - * @author senk.christian@googlemail.com - * @date 27.08.2010 - * @time 14:22:24 - * - */ -public @interface Serializable { - - Class[] value(); - -} diff --git a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/handler/DefaultMessageDispatchingHandler.java b/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/handler/DefaultMessageDispatchingHandler.java deleted file mode 100755 index 7e1c2659a8e..00000000000 --- a/java/de.csenk.gwt.ws/src/de/csenk/gwt/ws/shared/handler/DefaultMessageDispatchingHandler.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * 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 Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ - -package de.csenk.gwt.ws.shared.handler; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import de.csenk.gwt.ws.shared.Connection; -import de.csenk.gwt.ws.shared.ExceptionHandler; -import de.csenk.gwt.ws.shared.MessageDispatchingHandler; -import de.csenk.gwt.ws.shared.MessageHandler; - -/** - * @author senk.christian@googlemail.com - * @date 08.09.2010 - * @time 11:08:11 - * - */ -public abstract class DefaultMessageDispatchingHandler implements - MessageDispatchingHandler { - - private final Map, MessageHandler> receivedMessageHandlers = new HashMap, MessageHandler>(); - private final Map, ExceptionHandler> exceptionHandlers = new HashMap, ExceptionHandler>(); - - /* - * (non-Javadoc) - * - * @see - * de.csenk.gwt.ws.shared.MessageDispatchingHandler#addReceivedMessageHandler - * (java.lang.Class, de.csenk.gwt.ws.shared.MessageHandler) - */ - @Override - public synchronized void addReceivedMessageHandler(Class type, - MessageHandler handler) { - if (receivedMessageHandlers.containsKey(type)) - return; - - receivedMessageHandlers.put(type, handler); - } - - /* - * (non-Javadoc) - * - * @see - * de.csenk.gwt.ws.shared.MessageDispatchingHandler#addExceptionCaughtHandler - * (java.lang.Class, de.csenk.gwt.ws.shared.ExceptionHandler) - */ - @Override - public synchronized void addExceptionHandler( - Class type, ExceptionHandler handler) { - if (exceptionHandlers.containsKey(type)) - return; - - exceptionHandlers.put(type, handler); - } - - /* - * (non-Javadoc) - * - * @see - * de.csenk.gwt.ws.shared.Handler#onConnectionClosed(de.csenk.gwt.ws.shared - * .Connection) - */ - @Override - public void onConnectionClosed(Connection connection) throws Throwable { - } - - /* - * (non-Javadoc) - * - * @see - * de.csenk.gwt.ws.shared.Handler#onConnectionOpened(de.csenk.gwt.ws.shared - * .Connection) - */ - @Override - public void onConnectionOpened(Connection connection) throws Throwable { - } - - /* - * (non-Javadoc) - * - * @see - * de.csenk.gwt.ws.shared.Handler#onExceptionCaught(de.csenk.gwt.ws.shared - * .Connection, java.lang.Throwable) - */ - @Override - public void onExceptionCaught(Connection connection, Throwable caught) { - ExceptionHandler exceptionHandler = findExceptionHandler(caught - .getClass()); - if (exceptionHandler != null) { - exceptionHandler.handleException(connection, caught); - } - } - - /** - * @param type - * @return - */ - @SuppressWarnings("unchecked") - private ExceptionHandler findExceptionHandler(Class type) { - return (ExceptionHandler) findHandler(exceptionHandlers, - type, null); - } - - /* - * (non-Javadoc) - * - * @see - * de.csenk.gwt.ws.shared.Handler#onMessageReceived(de.csenk.gwt.ws.shared - * .Connection, java.lang.Object) - */ - @Override - public void onMessageReceived(Connection connection, Object message) - throws Throwable { - MessageHandler messageHandler = findReceivedMessageHandler(message - .getClass()); - if (messageHandler != null) { - messageHandler.handleMessage(connection, message); - } - } - - /** - * @param type - * @return - */ - @SuppressWarnings("unchecked") - private MessageHandler findReceivedMessageHandler(Class type) { - return (MessageHandler) findHandler(receivedMessageHandlers, - type, null); - } - - /** - * @param handlers - * @param type - * @param object - * @return - */ - @SuppressWarnings("rawtypes") - protected abstract Object findHandler(Map handlers, Class type, Set triedTypes); - -} diff --git a/java/pom.xml b/java/pom.xml index 3388a536239..5ea4b89f567 100755 --- a/java/pom.xml +++ b/java/pom.xml @@ -103,7 +103,6 @@ com.sap.sailing.nmeaconnector.test com.sap.sailing.simulator.test com.sap.sailing.server.trackfiles.test - de.csenk.gwt.ws com.sap.sailing.selenium.test com.sap.sailing.feature.p2build