repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/shared/grok/PositionTranslatorTest.java
javatests/com/google/collide/shared/grok/PositionTranslatorTest.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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 com.google.collide.shared.grok; import com.google.collide.shared.document.LineNumberAndColumn; import junit.framework.TestCase; /** * Unit test for PositionTranslator. * */ public class PositionTranslatorTest extends TestCase { public void testOffsetToLineNumber() { String src = "0123\n" + "56\n" + "\n" + "9"; PositionTranslator positionTranslator = new PositionTranslator(src); LineNumberAndColumn result = positionTranslator.getLineNumberAndColumn(0); assertEquals(0, result.lineNumber); assertEquals(0, result.column); result = positionTranslator.getLineNumberAndColumn(4); assertEquals(0, result.lineNumber); assertEquals(4, result.column); result = positionTranslator.getLineNumberAndColumn(5); assertEquals(1, result.lineNumber); assertEquals(0, result.column); result = positionTranslator.getLineNumberAndColumn(7); assertEquals(1, result.lineNumber); assertEquals(2, result.column); result = positionTranslator.getLineNumberAndColumn(8); assertEquals(2, result.lineNumber); assertEquals(0, result.column); result = positionTranslator.getLineNumberAndColumn(9); assertEquals(3, result.lineNumber); assertEquals(0, result.column); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/com/google/collide/json/shared/JsonIntegerMap.java
api/src/main/java/com/google/collide/json/shared/JsonIntegerMap.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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 com.google.collide.json.shared; /** * Integer Map interface. * * @param <T> the type contained as value in the map */ public interface JsonIntegerMap<T> { /** * Callback interface for int,double key value pairs. */ public interface IterationCallback<T> { void onIteration(int key, T val); } boolean hasKey(int key); T get(int key); void put(int key, T val); boolean isEmpty(); void erase(int key); /** * Iterates through the contents and calls back out to a callback. * * @param cb callback object */ void iterate(IterationCallback<T> cb); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/com/google/collide/json/shared/JsonArrayIterator.java
api/src/main/java/com/google/collide/json/shared/JsonArrayIterator.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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 com.google.collide.json.shared; import java.util.Iterator; import java.util.NoSuchElementException; /** * Implementation that iterates array without gaps in index, * * @param <T> items type * */ public class JsonArrayIterator<T> implements Iterator<T> { private int index; private final JsonArray<T> items; private boolean hasRemovedSinceNextCall; public JsonArrayIterator(JsonArray<T> items) { this.items = items; } @Override public boolean hasNext() { return index < items.size(); } @Override public T next() { if (index == items.size()) { throw new NoSuchElementException(); } T result = items.get(index); index++; hasRemovedSinceNextCall = false; return result; } @Override public void remove() { if (hasRemovedSinceNextCall || index == 0) { throw new IllegalStateException(); } index--; items.remove(index); hasRemovedSinceNextCall = true; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/com/google/collide/json/shared/JsonArray.java
api/src/main/java/com/google/collide/json/shared/JsonArray.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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 com.google.collide.json.shared; import java.util.Comparator; /** * Defines a simple interface for a list/array. * * When used with DTOs: * * On the client it is safe to cast this to a * {@link com.google.collide.json.client.JsoArray}. * * Native to JavaScript "sparse" arrays are not supported. * * On the server, this is an instance of * {@link com.google.collide.json.server.JsonArrayListAdapter} which * is a wrapper around a List. * */ public interface JsonArray<T> { void add(T item); void addAll(JsonArray<? extends T> item); void clear(); boolean contains(T item); JsonArray<T> copy(); T get(int index); int indexOf(T item); boolean isEmpty(); String join(String separator); T peek(); T pop(); T remove(int index); Iterable<T> asIterable(); boolean remove(T item); void reverse(); /** * Assigns a new value to the slot with specified index. * * @throws IndexOutOfBoundsException if index is not in [0..length) range */ void set(int index, T item); /** * Sorts the array according to the comparator. Mutates the array. */ void sort(Comparator<? super T> comparator); int size(); JsonArray<T> slice(int start, int end); JsonArray<T> splice(int index, int deleteCount, T value); JsonArray<T> splice(int index, int deleteCount); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/com/google/collide/json/shared/JsonStringMap.java
api/src/main/java/com/google/collide/json/shared/JsonStringMap.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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 com.google.collide.json.shared; /** * String Map interface for use in DTOs. * * On the client it is safe to cast this to a * {@link com.google.collide.json.client.Jso}. * * On the server this is an instance of a wrapper object * {@link com.google.collide.json.server.JsonStringMapAdapter}. */ public interface JsonStringMap<T> { /** * Callback to support iterating through the fields on this map. * * @param <T> */ public interface IterationCallback<T> { void onIteration(String key, T value); } T get(String key); JsonArray<String> getKeys(); boolean isEmpty(); void iterate(IterationCallback<T> callback); void put(String key, T value); void putAll(JsonStringMap<T> otherMap); /** * Removes the item with the given key, and returns it. */ T remove(String key); boolean containsKey(String key); int size(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/com/google/collide/json/shared/JsonObject.java
api/src/main/java/com/google/collide/json/shared/JsonObject.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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 com.google.collide.json.shared; /** * Defines a simple, mutable JSON object. */ public interface JsonObject { JsonObject addField(String key, boolean value); JsonObject addField(String key, double value); JsonObject addField(String key, int value); JsonObject addField(String key, JsonArray<?> value); JsonObject addField(String key, JsonObject value); JsonObject addField(String key, String value); boolean getBooleanField(String key); int getIntField(String key); JsonArray<String> getKeys(); JsonObject getObjectField(String key); JsonArray<?> getArrayField(String field); String getStringField(String key); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/com/google/collide/json/shared/JsonStringSet.java
api/src/main/java/com/google/collide/json/shared/JsonStringSet.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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 com.google.collide.json.shared; /** * String Set interface. */ public interface JsonStringSet { /** * Callback to support iterating through the keys of this set. */ public interface IterationCallback { void onIteration(String key); } boolean contains(String key); JsonArray<String> getKeys(); boolean isEmpty(); void iterate(IterationCallback callback); void add(String key); void addAll(JsonArray<String> keys); /** * Removes the item with the given key. * * @param key key of the item to be removed from this set, if present * @return <tt>true</tt> if this set contained the specified element */ boolean remove(String key); void clear(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/com/google/collide/dtogen/DtoGenerator.java
api/src/main/java/com/google/collide/dtogen/DtoGenerator.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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 com.google.collide.dtogen; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; import com.google.common.base.Charsets; import com.google.common.hash.HashCode; import com.google.common.hash.Hashing; import com.google.common.io.Files; import xapi.reflect.X_Reflect; /** * Simple source generator that takes in a jar of interface definitions and * generates client and server DTO impls. * */ public class DtoGenerator { private static final String SERVER = "server"; private static final String CLIENT = "client"; /** Flag: location of the input source dto jar. */ static String dto_jar = null; /** Flag: Name of the generated java class file that contains the DTOs. */ static String gen_file_name = "DataObjects.java"; /** Flag: The type of impls to be generated, either CLIENT or SERVER. */ static String impl = CLIENT; /** * Flag: A pattern we can use to search an absolute path and find the start * of the package definition.") */ static String package_base = "java."; /** * @param args */ public static void main(String[] args) { // First, calculate defaults. String myBase = X_Reflect.getFileLoc(DtoGenerator.class); if (File.separatorChar != '/') { myBase = myBase.replace(File.separatorChar, '/'); } String buildDir = "api" + File.separator + "build" + File.separator; myBase = myBase // first, replace the path when running from compiled classes (via IDE) .replace(buildDir + "classes" + File.separator + "main" + File.separator, "") // then, if running from compiled jar; // if you are creating another executable jar somewhere else, // then you will need to supply command line argument overrides. .replaceFirst(buildDir + "libs" + File.separator + ".*[.]jar", "") ; dto_jar = myBase + "shared/build/libs/shared-0.5.1-SNAPSHOT.jar"; gen_file_name = myBase + "client/src/main/java/com/google/collide/dto/client/DtoClientImpls.java"; impl = "client"; package_base = "java"; // Now, check for cli overrides for (String arg : args) { if (arg.startsWith("--dto_jar=")) { dto_jar = arg.substring("--dto_jar=".length()); } else if (arg.startsWith("--gen_file_name=")) { gen_file_name = arg.substring("--gen_file_name=".length()); } else if (arg.startsWith("--impl=")) { impl = arg.substring("--impl=".length()); } else if (arg.startsWith("--package_base=")) { package_base = arg.substring("--package_base=".length()); } else { System.err.println("Unknown flag: " + arg); System.exit(1); } } String outputFilePath = gen_file_name; // Extract the name of the output file that will contain all the DTOs and // its package. int packageStart = outputFilePath.indexOf(package_base) + package_base.length(); int packageEnd = outputFilePath.lastIndexOf('/'); String fileName = outputFilePath.substring(packageEnd + 1); String className = fileName.substring(0, fileName.indexOf(".java")); String packageName = outputFilePath.substring(packageStart + 1, packageEnd).replace('/', '.'); File outFile = new File(outputFilePath); File interfaceJar = new File(dto_jar); try { DtoTemplate dtoTemplate = new DtoTemplate( packageName, className, getApiHash(interfaceJar), impl.equals(SERVER)); // Crack open the JAR that contains the class files for the DTO // interfaces. Collect class files to load. List<String> classFilePaths = new ArrayList<String>(); try(JarFile jarFile = new JarFile(interfaceJar);){ Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { String entryFilePath = entries.nextElement().getName(); if (isValidClassFile(entryFilePath)) { classFilePaths.add(entryFilePath); } } }finally{} // Load the classes that we found above. URL[] urls = {interfaceJar.toURI().toURL()}; URLClassLoader loader = new URLClassLoader(urls); // We sort alphabetically to ensure deterministic order of routing types. Collections.sort(classFilePaths); for (String classFilePath : classFilePaths) { URL resource = loader.findResource(classFilePath); if (resource != null) { String javaName = classFilePath.replace('/', '.').substring(0, classFilePath.lastIndexOf(".class")); Class<?> dtoInterface = Class.forName(javaName, false, loader); if (dtoInterface.isInterface()) { // Add interfaces to the DtoTemplate. dtoTemplate.addInterface(dtoInterface); } } } // Emit the generated file, only if it has changed (prevents spurious gwt recompile). String outputFile = dtoTemplate.toString(); if (outFile.exists()) { String current = Files.toString(outFile, Charsets.UTF_8); if (current.equals(outputFile)) { System.err.println("Skipping dto generation as output file already matches generated values"); return; } } BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); writer.write(outputFile); writer.close(); } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private static boolean isValidClassFile(String file) { return file.endsWith(".class") && file.contains("dto"); } private static String getApiHash(File interfaceJar) throws IOException { byte[] fileBytes = Files.toByteArray(interfaceJar); HashCode hashCode = Hashing.sha1().hashBytes(fileBytes); return hashCode.toString(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/com/google/collide/dtogen/DtoImplClientTemplate.java
api/src/main/java/com/google/collide/dtogen/DtoImplClientTemplate.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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 com.google.collide.dtogen; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List; import com.google.collide.dtogen.shared.ClientToServerDto; import com.google.collide.dtogen.shared.RoutableDto; import com.google.collide.dtogen.shared.SerializationIndex; import com.google.collide.dtogen.shared.ServerToClientDto; import com.google.collide.json.shared.JsonArray; import com.google.collide.json.shared.JsonStringMap; import com.google.common.base.Preconditions; /** * Generates the source code for a generated Client DTO impl. * */ public class DtoImplClientTemplate extends DtoImpl { private static final String ROUTABLE_DTO_IMPL = RoutableDto.class.getPackage().getName().replace("dtogen.shared", "dtogen.client") + ".RoutableDtoClientImpl"; private static final String JSO_TYPE = "com.google.collide.json.client.Jso"; private static boolean isEnum(Class<?> type) { return type != null && (type.equals(Enum.class) || isEnum(type.getSuperclass())); } DtoImplClientTemplate(DtoTemplate template, int routingType, Class<?> dtoInterface) { super(template, routingType, dtoInterface); } @Override String serialize() { StringBuilder builder = new StringBuilder(); Class<?> dtoInterface = getDtoInterface(); List<Method> methods = getDtoMethods(); emitPreamble(dtoInterface, builder); emitMethods(methods, builder); // Only emit a factory method if the supertype is a ClientToServerDto or is // non-routable. if (DtoTemplate.implementsClientToServerDto(dtoInterface) || getRoutingType() == RoutableDto.NON_ROUTABLE_TYPE) { emitFactoryMethod(builder); } else { builder.append("\n }\n"); // emit testing mock, with factory, as a separate subclass emitMockPreamble(dtoInterface, builder); emitFactoryMethod(builder); } builder.append(" }\n"); return builder.toString(); } /** * Emits a factory method that trivially returns a new Javascript object with * the type set. */ private void emitFactoryMethod(StringBuilder builder) { builder.append("\n public static native "); builder.append(getImplClassName()); builder.append(" make() /*-{\n"); if (isCompactJson()) { builder.append(" return [];"); } else { builder.append(" return {\n"); if (getRoutingType() != RoutableDto.NON_ROUTABLE_TYPE) { emitKeyValue(RoutableDto.TYPE_FIELD, Integer.toString(getRoutingType()), builder); } builder.append("\n };"); } builder.append("\n }-*/;"); } private void emitHasMethod(String methodName, String fieldSelector, StringBuilder builder) { builder.append("\n public final native boolean ").append(methodName).append("() /*-{\n"); builder.append(" return this.hasOwnProperty(").append(fieldSelector).append(");\n"); builder.append(" }-*/;\n"); } private void emitGetter(Method method, String methodName, String fieldSelector, String returnType, StringBuilder builder) { builder.append("\n @Override\n public final native "); builder.append(returnType); builder.append(" "); builder.append(methodName); builder.append("() /*-{\n"); if (isCompactJson()) { // We can omit last members in list it they do not carry any information. // Currently we skip only one member, and only if it is an array. // We can add more cases and more robust "tail" detection in the future. if (isLastMethod(method)) { List<Type> expandedTypes = expandType(method.getGenericReturnType()); if (isJsonArray(getRawClass(expandedTypes.get(0)))) { builder.append(" if (!this.hasOwnProperty(").append(fieldSelector).append(")) {\n"); builder.append(" this[").append(fieldSelector).append("] = [];\n"); builder.append(" }\n"); } } } emitReturn(method, fieldSelector, builder); builder.append(" }-*/;\n"); } private void emitKeyValue(String fieldName, String value, StringBuilder builder) { builder.append(" "); builder.append(fieldName); builder.append(": "); builder.append(value); } private void emitMethods(List<Method> methods, StringBuilder builder) { for (Method method : methods) { if (ignoreMethod(method)) { continue; } String methodName = method.getName(); String fieldName = getFieldName(methodName); String fieldSelector; if (isCompactJson()) { SerializationIndex serializationIndex = Preconditions.checkNotNull( method.getAnnotation(SerializationIndex.class)); fieldSelector = String.valueOf(serializationIndex.value() - 1); } else { fieldSelector = "\"" + getFieldName(methodName) + "\""; } String returnTypeName = method.getGenericReturnType().toString().replace('$', '.').replace("class ", "") .replace("interface ", ""); // Native JSNI Getter. emitGetter(method, methodName, fieldSelector, returnTypeName, builder); // Native JSNI Setter emitSetter(getSetterName(fieldName), fieldName, fieldSelector, method.getGenericReturnType(), returnTypeName, getImplClassName(), builder); emitHasMethod("has" + getCamelCaseName(fieldName), fieldSelector, builder); } } private void emitMockPreamble(Class<?> dtoInterface, StringBuilder builder) { builder.append("\n\n public static class Mock"); builder.append(getImplClassName()); builder.append(" extends "); builder.append(getImplClassName()); builder.append(" {\n protected Mock"); builder.append(getImplClassName()); builder.append("() {}\n"); } private void emitPreamble(Class<?> dtoInterface, StringBuilder builder) { builder.append("\n\n public static class "); builder.append(getImplClassName()); builder.append(" extends "); Class<?> superType = getSuperInterface(); if (superType != null) { // We special case ServerToClientDto and ClientToServerDto since their // impls are not generated. if (superType.equals(ServerToClientDto.class) || superType.equals(ClientToServerDto.class)) { builder.append(ROUTABLE_DTO_IMPL); } else { builder.append(superType.getSimpleName() + "Impl"); } } else { // Just a plain Jso. builder.append(JSO_TYPE); } boolean isSerializable = isSerializable(); builder.append(" implements "); builder.append(dtoInterface.getCanonicalName()); if (isSerializable){ builder.append(", java.io.Serializable"); } builder.append(" {\n protected "); builder.append(getImplClassName()); builder.append("() {}\n"); if (isSerializable){ builder.append(" private static final long serialVersionUID = " +dtoInterface.getCanonicalName().hashCode()+"L;\n"); } } private void emitReturn(Method method, String fieldSelector, StringBuilder builder) { Type type = method.getGenericReturnType(); Class<?> rawClass = getRawClass(type); String thisFieldName = "this[" + fieldSelector + "]"; if (type instanceof ParameterizedType) { List<Type> expandedTypes = expandType(type); if (hasEnum(expandedTypes)) { final String tmpVar = "_tmp"; emitReturnEnumReplacement(expandedTypes, 0, thisFieldName, tmpVar, " ", builder); builder.append(" return ").append(tmpVar).append(";\n"); return; } } builder.append(" return "); if (isEnum(method.getReturnType())) { // Gson serializes enums with their toString() representation emitEnumValueOf(rawClass, thisFieldName, builder); } else { builder.append(thisFieldName); } builder.append(";\n"); } private void emitReturnEnumReplacement(List<Type> types, int i, String inVar, String outVar, String indentation, StringBuilder builder) { Class<?> rawClass = getRawClass(types.get(i)); String tmpVar = "tmp" + i; String childInVar = "in" + (i + 1); String childOutVar = "out" + (i + 1); if (isJsonArray(rawClass)) { // tmpVar is the index builder.append(indentation).append(outVar).append(" = [];\n"); builder.append(indentation).append(inVar).append(".forEach(function(").append(childInVar) .append(", ").append(tmpVar).append(") {\n"); } else if (isEnum(rawClass)) { builder.append(indentation).append(outVar).append(" = "); emitEnumValueOf(rawClass, inVar, builder); builder.append(";\n"); } else if (isJsonStringMap(rawClass)) { // TODO: implement when needed throw new IllegalStateException("enums inside JsonStringMaps need to be implemented"); } if (i + 1 < types.size()) { emitReturnEnumReplacement(types, i + 1, childInVar, childOutVar, indentation + " ", builder); } if (isJsonArray(rawClass)) { builder.append(indentation).append(" ").append(outVar).append("[").append(tmpVar) .append("] = ").append(childOutVar).append(";\n"); builder.append(indentation).append("});\n"); } } private void emitEnumValueOf(Class<?> rawClass, String var, StringBuilder builder) { builder.append(var); builder.append("? @"); builder.append(rawClass.getCanonicalName()); builder.append("::valueOf(Ljava/lang/String;)("); builder.append(var); builder.append(")"); builder.append(": null"); } private void emitSetter(String methodName, String fieldName, String fieldSelector, Type type, String paramTypeName, String returnType, StringBuilder builder) { builder.append("\n public final native "); builder.append(returnType); builder.append(" "); builder.append(methodName); builder.append("("); emitSetterParameterTypeName(getRawClass(type), paramTypeName, builder); builder.append(" "); builder.append(fieldName); builder.append(") /*-{\n"); emitSetterPropertyAssignment(fieldName, fieldSelector, type, builder); builder.append(" return this;\n }-*/;\n"); } private void emitSetterParameterTypeName(Class<?> paramType, String paramTypeName, StringBuilder builder) { /* * For our Json collections, require the concrete client-side type since we * call JSON.stringify on this DTO. */ if (paramType == JsonArray.class) { paramTypeName = paramTypeName.replace("com.google.collide.json.shared.JsonArray", "com.google.collide.json.client.JsoArray"); } else if (paramType == JsonStringMap.class) { paramTypeName = paramTypeName.replace("com.google.collide.json.shared.JsonStringMap", "com.google.collide.json.client.JsoStringMap"); } builder.append(paramTypeName); } private void emitSetterPropertyAssignment( String fieldName, String fieldSelector, Type type, StringBuilder builder) { Class<?> rawClass = getRawClass(type); if (type instanceof ParameterizedType) { List<Type> expandedTypes = expandType(type); if (hasEnum(expandedTypes)) { final String tmpVar = "_tmp"; builder.append(" ").append(tmpVar).append(" = ").append(fieldName).append(";\n"); emitSetterEnumReplacement(expandedTypes, 0, tmpVar, fieldName, " ", builder); } } else if (isEnum(rawClass)) { /*- * codeBlockType = * codeBlockType.@com.google.collide.dto.CodeBlock.Type:: * toString()() */ builder.append(" ").append(fieldName).append(" = "); emitEnumToString(rawClass, fieldName, builder); builder.append(";\n"); } builder.append(" this["); builder.append(fieldSelector); builder.append("] = "); builder.append(fieldName); builder.append(";\n"); } private boolean hasEnum(List<Type> types) { for (Type type : types) { if (isEnum(getRawClass(type))) { return true; } } return false; } private void emitSetterEnumReplacement(List<Type> types, int i, String inVar, String outVar, String indentation, StringBuilder builder) { Class<?> rawClass = getRawClass(types.get(i)); String tmpVar = "tmp" + i; String childInVar = "in" + (i + 1); String childOutVar = "out" + (i + 1); if (isJsonArray(rawClass)) { builder.append(indentation).append(tmpVar).append(" = [];\n"); builder.append(indentation).append(inVar).append(".forEach(function(").append(childInVar) .append(") {\n"); } else if (isEnum(rawClass)) { builder.append(indentation).append(outVar).append(" = "); emitEnumToString(rawClass, inVar, builder); builder.append(";\n"); } else if (isJsonStringMap(rawClass)) { // TODO: implement when needed throw new IllegalStateException("enums inside JsonStringMaps need to be implemented"); } if (i + 1 < types.size()) { emitSetterEnumReplacement(types, i + 1, childInVar, childOutVar, indentation + " ", builder); } if (isJsonArray(rawClass)) { builder.append(indentation).append(" ").append(tmpVar).append(".push(").append(childOutVar) .append(");\n"); builder.append(indentation).append("});\n"); builder.append(indentation).append(outVar).append(" = ").append(tmpVar).append(";\n"); } } private void emitEnumToString(Class<?> enumClass, String fieldName, StringBuilder builder) { builder.append(fieldName); builder.append(".@"); builder.append(enumClass.getCanonicalName()); builder.append("::toString()()"); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/com/google/collide/dtogen/DtoImplServerTemplate.java
api/src/main/java/com/google/collide/dtogen/DtoImplServerTemplate.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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 com.google.collide.dtogen; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.google.collide.dtogen.shared.ClientToServerDto; import com.google.collide.dtogen.shared.RoutableDto; import com.google.collide.dtogen.shared.SerializationIndex; import com.google.collide.dtogen.shared.ServerToClientDto; import com.google.collide.json.shared.JsonArray; import com.google.collide.json.shared.JsonStringMap; import com.google.common.base.Preconditions; import com.google.common.primitives.Primitives; /** * Generates the source code for a generated Server DTO impl. * */ public class DtoImplServerTemplate extends DtoImpl { private static final String JSON_ARRAY = JsonArray.class.getCanonicalName(); private static final String JSON_ARRAY_ADAPTER = JsonStringMap.class.getPackage().getName().replace(".shared", ".server.JsonArrayListAdapter"); private static final String JSON_MAP = JsonStringMap.class.getCanonicalName(); private static final String JSON_MAP_ADAPTER = JsonStringMap.class.getPackage().getName().replace(".shared", ".server.JsonStringMapAdapter"); private static final String ROUTABLE_DTO_IMPL = RoutableDto.class.getPackage().getName().replace("dtogen.shared", "dtogen.server") + ".RoutableDtoServerImpl"; DtoImplServerTemplate(DtoTemplate template, int routingType, Class<?> superInterface) { super(template, routingType, superInterface); } @Override String serialize() { StringBuilder builder = new StringBuilder(); Class<?> dtoInterface = getDtoInterface(); List<Method> methods = getDtoMethods(); emitPreamble(dtoInterface, builder); // Enumerate the getters and emit field names and getters + setters. emitFields(methods, builder); emitMethods(methods, builder); emitEqualsAndHashcode(methods, builder); emitSerializer(methods, builder); emitDeserializer(methods, builder); emitDeserializerShortcut(methods, builder); builder.append(" }\n"); // Emit a testing mock emitMockPreamble(dtoInterface, builder); builder.append(" }\n"); return builder.toString(); } private void emitDefaultRoutingTypeConstructor(StringBuilder builder) { builder.append(" private "); builder.append(getImplClassName()); builder.append("() {"); builder.append("\n super("); builder.append("" + getRoutingType()); builder.append(");\n "); builder.append("}\n\n"); } private void emitEqualsAndHashcode(List<Method> methods, StringBuilder builder) { builder.append("\n"); builder.append(" @Override\n"); builder.append(" public boolean equals(Object o) {\n"); // if this class inherits from anything, check that the superclass fields are also equal Class<?> superType = getSuperInterface(); if (superType != null) { builder.append(" if (!super.equals(o)) {\n"); builder.append(" return false;\n"); builder.append(" }\n"); } builder.append(" if (!(o instanceof " + getImplClassName() + ")) {\n"); builder.append(" return false;\n"); builder.append(" }\n"); builder.append(" " + getImplClassName() + " other = (" + getImplClassName() + ") o;\n"); for (Method method : methods) { if (!ignoreMethod(method)) { String fieldName = getFieldName(method.getName()); String hasFieldName = getHasFieldName(fieldName); builder.append(" if (this." + hasFieldName + " != other." + hasFieldName + ") {\n"); builder.append(" return false;\n"); builder.append(" }\n"); builder.append(" if (this." + hasFieldName + ") {\n"); if (method.getReturnType().isPrimitive()) { builder.append(" if (this." + fieldName + " != other." + fieldName + ") {\n"); } else { builder.append(" if (!this." + fieldName + ".equals(other." + fieldName + ")) {\n"); } builder.append(" return false;\n"); builder.append(" }\n"); builder.append(" }\n"); } } builder.append(" return true;\n"); builder.append(" }\n"); // this isn't the greatest hash function in the world, but it meets the requirement that for any // two objects A and B, A.equals(B) only if A.hashCode() == B.hashCode() builder.append("\n"); builder.append(" @Override\n"); builder.append(" public int hashCode() {\n"); // if this class inherits from anything, include the superclass hashcode if (superType != null) { builder.append(" int hash = super.hashCode();\n"); } else { builder.append(" int hash = 1;\n"); } for (Method method : methods) { if (!ignoreMethod(method)) { Class<?> type = method.getReturnType(); String fieldName = getFieldName(method.getName()); builder.append(" hash = hash * 31 + (" + getHasFieldName(fieldName) + " ? "); if (type.isPrimitive()) { Class<?> wrappedType = Primitives.wrap(type); builder.append(wrappedType.getName() + ".valueOf(" + fieldName + ").hashCode()"); } else { builder.append(fieldName + ".hashCode()"); } builder.append(" : 0);\n"); } } builder.append(" return hash;\n"); builder.append(" }\n"); } private void emitFactoryMethod(StringBuilder builder) { builder.append(" public static "); builder.append(getImplClassName()); builder.append(" make() {"); builder.append("\n return new "); builder.append(getImplClassName()); builder.append("();\n }\n\n"); } private void emitFields(List<Method> methods, StringBuilder builder) { for (Method method : methods) { if (!ignoreMethod(method)) { String methodName = method.getName(); String fieldName = getFieldName(methodName); builder.append(" "); builder.append(getFieldTypeAndAssignment(method, fieldName)); // Emit a boolean to track whether the DTO has the field. builder.append(" private boolean "); builder.append(getHasFieldName(fieldName)); builder.append(";\n"); } } } private void emitHasField(String fieldName, StringBuilder builder) { String camelCaseFieldName = getCamelCaseName(fieldName); builder.append("\n public boolean has"); builder.append(camelCaseFieldName); builder.append("() {\n"); builder.append(" return "); builder.append(getHasFieldName(fieldName)); builder.append(";\n }\n"); } /** * Emits a method to get a field. Getting a collection ensures that the collection * is created. */ private void emitGetter(Method method, String methodName, String fieldName, String returnType, StringBuilder builder) { builder.append("\n @Override\n public "); builder.append(returnType); builder.append(" "); builder.append(methodName); builder.append("() {\n"); // Initialize the collection. Class<?> returnTypeClass = method.getReturnType(); if (isJsonArray(returnTypeClass) || isJsonStringMap(returnTypeClass)) { builder.append(" "); builder.append(getEnsureName(fieldName)); builder.append("();\n"); } builder.append(" return "); emitReturn(method, fieldName, builder); builder.append(";\n }\n"); } private void emitMethods(List<Method> methods, StringBuilder builder) { for (Method method : methods) { if (ignoreMethod(method)) { continue; } String methodName = method.getName(); String fieldName = getFieldName(methodName); Class<?> returnTypeClass = method.getReturnType(); String returnType = method .getGenericReturnType() .toString() .replace('$', '.') .replace("class ", "") .replace("interface ", ""); // HasField. emitHasField(fieldName, builder); // Getter. emitGetter(method, methodName, fieldName, returnType, builder); // Setter. emitSetter(method, getImplClassName(), fieldName, builder); // List-specific methods. if (isJsonArray(returnTypeClass)) { emitListAdd(method, fieldName, builder); emitClear(fieldName, builder); emitEnsureCollection(method, fieldName, builder); } else if (isJsonStringMap(returnTypeClass)) { emitMapPut(method, fieldName, builder); emitClear(fieldName, builder); emitEnsureCollection(method, fieldName, builder); } } } private void emitSerializer(List<Method> methods, StringBuilder builder) { builder.append("\n @Override\n"); builder.append(" public JsonElement toJsonElement() {\n"); if (isCompactJson()) { builder.append(" JsonArray result = new JsonArray();\n"); for (Method method : methods) { emitSerializeFieldForMethodCompact(method, builder); } } else { builder.append(" JsonObject result = new JsonObject();\n"); for (Method method : methods) { emitSerializeFieldForMethod(method, builder); } } builder.append(" return result;\n"); builder.append(" }\n"); builder.append("\n"); builder.append(" @Override\n"); builder.append(" public String toJson() {\n"); builder.append(" return gson.toJson(toJsonElement());\n"); builder.append(" }\n"); builder.append("\n"); builder.append(" @Override\n"); builder.append(" public String toString() {\n"); builder.append(" return toJson();\n"); builder.append(" }\n"); } private void emitSerializeFieldForMethod(Method method, final StringBuilder builder) { if (method.getName().equals("getType")) { String typeFieldName = "_type"; if (getRoutingType() == RoutableDto.NON_ROUTABLE_TYPE) { typeFieldName = "type"; } builder.append(" result.add(\"" + typeFieldName + "\", new JsonPrimitive(getType()));\n"); return; } final String fieldName = getFieldName(method.getName()); final String fieldNameOut = fieldName + "Out"; final String baseIndentation = " "; builder.append("\n"); List<Type> expandedTypes = expandType(method.getGenericReturnType()); emitSerializerImpl(expandedTypes, 0, builder, fieldName, fieldNameOut, baseIndentation); builder.append(" result.add(\"" + fieldName + "\", ").append(fieldNameOut).append(");\n"); } private void emitSerializeFieldForMethodCompact(Method method, StringBuilder builder) { if (method == null) { builder.append(" result.add(JsonNull.INSTANCE);\n"); return; } final String fieldName = getFieldName(method.getName()); final String fieldNameOut = fieldName + "Out"; final String baseIndentation = " "; builder.append("\n"); List<Type> expandedTypes = expandType(method.getGenericReturnType()); emitSerializerImpl(expandedTypes, 0, builder, fieldName, fieldNameOut, baseIndentation); if (isLastMethod(method)) { if (isJsonArray(getRawClass(expandedTypes.get(0)))) { builder.append(" if (").append(fieldNameOut).append(".size() != 0) {\n"); builder.append(" result.add(").append(fieldNameOut).append(");\n"); builder.append(" }\n"); return; } } builder.append(" result.add(").append(fieldNameOut).append(");\n"); } /** * Produces code to serialize the type with the given variable names. * * @param expandedTypes the type and its generic (and its generic (..)) * expanded into a list, @see {@link #expandType(Type)} * @param depth the depth (in the generics) for this recursive call. This can * be used to index into {@code expandedTypes} * @param inVar the java type that will be the input for serialization * @param outVar the JsonElement subtype that will be the output for * serialization * @param i indentation string */ private void emitSerializerImpl(List<Type> expandedTypes, int depth, StringBuilder builder, String inVar, String outVar, String i) { Type type = expandedTypes.get(depth); String childInVar = inVar + "_"; String childOutVar = outVar + "_"; String entryVar = "entry" + depth; Class<?> rawClass = getRawClass(type); if (isJsonArray(rawClass)) { String childInTypeName = getImplName(expandedTypes.get(depth + 1), false); builder.append(i).append("JsonArray ").append(outVar).append(" = new JsonArray();\n"); if (depth == 0) { builder.append(i).append(getEnsureName(inVar)).append("();\n"); } builder.append(i).append("for (").append(childInTypeName).append(" ") .append(childInVar).append(" : ").append(inVar).append(") {\n"); } else if (isJsonStringMap(rawClass)) { String childInTypeName = getImplName(expandedTypes.get(depth + 1), false); builder.append(i).append("JsonObject ").append(outVar).append(" = new JsonObject();\n"); if (depth == 0) { builder.append(i).append(getEnsureName(inVar)).append("();\n"); } builder.append(i).append("for (Map.Entry<String, ").append(childInTypeName).append("> ") .append(entryVar).append(" : ").append(inVar).append(".entrySet()) {\n"); builder.append(i).append(" ").append(childInTypeName).append(" ").append(childInVar) .append(" = ").append(entryVar).append(".getValue();\n"); } else if (rawClass.isEnum()) { builder.append(i).append("JsonElement ").append(outVar).append(" = (").append(inVar) .append(" == null) ? JsonNull.INSTANCE : new JsonPrimitive(").append(inVar) .append(".name());\n"); } else if (getEnclosingTemplate().isDtoInterface(rawClass)) { builder.append(i).append("JsonElement ").append(outVar).append(" = ").append(inVar) .append(" == null ? JsonNull.INSTANCE : ").append(inVar).append(".toJsonElement();\n"); } else if (rawClass.equals(String.class)) { builder.append(i).append("JsonElement ").append(outVar) .append(" = (").append(inVar).append(" == null) ? JsonNull.INSTANCE : new JsonPrimitive(") .append(inVar).append(");\n"); } else { builder.append(i).append("JsonPrimitive ").append(outVar).append(" = new JsonPrimitive(") .append(inVar).append(");\n"); } if (depth + 1 < expandedTypes.size()) { emitSerializerImpl(expandedTypes, depth + 1, builder, childInVar, childOutVar, i + " "); } if (isJsonArray(rawClass)) { builder.append(i).append(" ").append(outVar).append(".add(").append(childOutVar) .append(");\n"); builder.append(i).append("}\n"); } else if (isJsonStringMap(rawClass)) { builder.append(i).append(" ").append(outVar).append(".add(").append(entryVar) .append(".getKey(), ").append(childOutVar).append(");\n"); builder.append(i).append("}\n"); } } /** * Generates a static factory method that creates a new instance based * on a JsonElement. */ private void emitDeserializer(List<Method> methods, StringBuilder builder) { builder.append("\n public static "); builder.append(getImplClassName()); builder.append(" fromJsonElement(JsonElement jsonElem) {\n"); builder.append(" if (jsonElem == null || jsonElem.isJsonNull()) {\n"); builder.append(" return null;\n"); builder.append(" }\n\n"); builder.append(" ").append(getImplClassName()).append(" dto = new ") .append(getImplClassName()).append("();\n"); if (methods.size() > 0) { if (isCompactJson()) { builder.append(" JsonArray json = jsonElem.getAsJsonArray();\n"); for (Method method : methods) { if (method == null) { continue; } emitDeserializeFieldForMethodCompact(method, builder); } } else { builder.append(" JsonObject json = jsonElem.getAsJsonObject();\n"); for (Method method : methods) { emitDeserializeFieldForMethod(method, builder); } } } builder.append("\n return dto;\n"); builder.append(" }"); } private void emitDeserializerShortcut(List<Method> methods, StringBuilder builder) { builder.append("\n"); builder.append(" public static "); builder.append(getImplClassName()); builder.append(" fromJsonString(String jsonString) {\n"); builder.append(" if (jsonString == null) {\n"); builder.append(" return null;\n"); builder.append(" }\n\n"); builder.append(" return fromJsonElement(new JsonParser().parse(jsonString));\n"); builder.append(" }\n"); } private void emitDeserializeFieldForMethod(Method method, final StringBuilder builder) { if (method.getName().equals("getType")) { // The type is set in the constructor. return; } final String fieldName = getFieldName(method.getName()); final String fieldNameIn = fieldName + "In"; final String fieldNameOut = fieldName + "Out"; final String baseIndentation = " "; builder.append("\n"); builder.append(" if (json.has(\"").append(fieldName).append("\")) {\n"); List<Type> expandedTypes = expandType(method.getGenericReturnType()); builder.append(" JsonElement ").append(fieldNameIn).append(" = json.get(\"") .append(fieldName).append("\");\n"); emitDeserializerImpl(expandedTypes, 0, builder, fieldNameIn, fieldNameOut, baseIndentation); builder.append(" dto.").append(getSetterName(fieldName)).append("(") .append(fieldNameOut).append(");\n"); builder.append(" }\n"); } private void emitDeserializeFieldForMethodCompact( Method method, final StringBuilder builder) { final String fieldName = getFieldName(method.getName()); final String fieldNameIn = fieldName + "In"; final String fieldNameOut = fieldName + "Out"; final String baseIndentation = " "; SerializationIndex serializationIndex = Preconditions.checkNotNull( method.getAnnotation(SerializationIndex.class)); int index = serializationIndex.value() - 1; builder.append("\n"); builder.append(" if (").append(index).append(" < json.size()) {\n"); List<Type> expandedTypes = expandType(method.getGenericReturnType()); builder.append(" JsonElement ").append(fieldNameIn).append(" = json.get(") .append(index).append(");\n"); emitDeserializerImpl(expandedTypes, 0, builder, fieldNameIn, fieldNameOut, baseIndentation); builder.append(" dto.").append(getSetterName(fieldName)).append("(") .append(fieldNameOut).append(");\n"); builder.append(" }\n"); } /** * Produces code to deserialize the type with the given variable names. * * @param expandedTypes the type and its generic (and its generic (..)) * expanded into a list, @see {@link #expandType(Type)} * @param depth the depth (in the generics) for this recursive call. This can * be used to index into {@code expandedTypes} * @param inVar the java type that will be the input for serialization * @param outVar the JsonElement subtype that will be the output for * serialization * @param i indentation string */ private void emitDeserializerImpl(List<Type> expandedTypes, int depth, StringBuilder builder, String inVar, String outVar, String i) { Type type = expandedTypes.get(depth); String childInVar = inVar + "_"; String childOutVar = outVar + "_"; Class<?> rawClass = getRawClass(type); if (isJsonArray(rawClass)) { String inVarIterator = inVar + "Iterator"; builder.append(i).append(getImplName(type, false)).append(" ").append(outVar) .append(" = null;\n"); builder.append(i).append("if (").append(inVar).append(" != null && !").append(inVar) .append(".isJsonNull()) {\n"); builder.append(i).append(" ").append(outVar).append(" = new ") .append(getImplName(type, false)).append("();\n"); builder.append(i).append(" ").append(getImplName(Iterator.class, true)) .append("<JsonElement> ").append(inVarIterator).append(" = ").append(inVar) .append(".getAsJsonArray().iterator();\n"); builder.append(i).append(" while (").append(inVarIterator).append(".hasNext()) {\n"); builder.append(i).append(" JsonElement ").append(childInVar).append(" = ") .append(inVarIterator).append(".next();\n"); emitDeserializerImpl(expandedTypes, depth + 1, builder, childInVar, childOutVar, i + " "); builder.append(i).append(" ").append(outVar).append(".add(").append(childOutVar) .append(");\n"); builder.append(i).append(" }\n"); builder.append(i).append("}\n"); } else if (isJsonStringMap(rawClass)) { // TODO: Handle type String entryVar = "entry" + depth; String entriesVar = "entries" + depth; builder.append(i).append(getImplName(type, false)).append(" ").append(outVar) .append(" = null;\n"); builder.append(i).append("if (").append(inVar).append(" != null && !").append(inVar) .append(".isJsonNull()) {\n"); builder.append(i).append(" ").append(outVar).append(" = new ") .append(getImplName(type, false)).append("();\n"); builder.append(i).append(" java.util.Set<Map.Entry<String, JsonElement>> ") .append(entriesVar).append(" = ").append(inVar) .append(".getAsJsonObject().entrySet();\n"); builder.append(i).append(" for (Map.Entry<String, JsonElement> ").append(entryVar) .append(" : ").append(entriesVar).append(") {\n"); builder.append(i).append(" JsonElement ").append(childInVar).append(" = ") .append(entryVar).append(".getValue();\n"); emitDeserializerImpl(expandedTypes, depth + 1, builder, childInVar, childOutVar, i + " "); builder.append(i).append(" ").append(outVar).append(".put(").append(entryVar) .append(".getKey(), ").append(childOutVar).append(");\n"); builder.append(i).append(" }\n"); builder.append(i).append("}\n"); } else if (getEnclosingTemplate().isDtoInterface(rawClass)) { String implClassName = getImplName(rawClass, false); builder.append(i).append(implClassName).append(" ").append(outVar).append(" = ") .append(implClassName).append(".fromJsonElement(").append(inVar).append(");\n"); } else if (rawClass.isPrimitive()) { String primitiveName = rawClass.getSimpleName(); String primitiveNameCap = primitiveName.substring(0, 1).toUpperCase() + primitiveName.substring(1); builder.append(i).append(primitiveName).append(" ").append(outVar).append(" = ") .append(inVar).append(".getAs").append(primitiveNameCap).append("();\n"); } else { // Use gson to handle all other types. String rawClassName = rawClass.getName().replace('$', '.'); builder.append(i).append(rawClassName).append(" ").append(outVar).append(" = gson.fromJson(") .append(inVar).append(", ").append(rawClassName).append(".class);\n"); } } private void emitMockPreamble(Class<?> dtoInterface, StringBuilder builder) { builder.append("\n public static class "); builder.append("Mock" + getImplClassName()); builder.append(" extends "); builder.append(getImplClassName()); builder.append(" {\n"); builder.append(" protected Mock"); builder.append(getImplClassName()); builder.append("() {}\n\n"); emitFactoryMethod(builder); } private void emitPreamble(Class<?> dtoInterface, StringBuilder builder) { builder.append("\n public static class "); builder.append(getImplClassName()); Class<?> superType = getSuperInterface(); boolean isSerializable = isSerializable(); if (superType != null) { // We need to extend something. builder.append(" extends "); if (superType.equals(ServerToClientDto.class) || superType.equals(ClientToServerDto.class)) { // We special case RoutableDto's impl since it isnt generated. builder.append(ROUTABLE_DTO_IMPL); } else { builder.append(superType.getSimpleName() + "Impl"); } } builder.append(" implements "); builder.append(dtoInterface.getCanonicalName()); builder.append(", JsonSerializable"); if (isSerializable){ builder.append(", java.io.Serializable"); //also allow these objects to be stored in SharedData builder.append(", org.vertx.java.core.shareddata.Shareable"); } builder.append(" {\n\n"); if (isSerializable){ builder.append(" private static final long serialVersionUID = " +dtoInterface.getCanonicalName().hashCode()+"L;\n"); } // If this guy is Routable, we make two constructors. One is a private // default constructor that hard codes the routing type, the other is a // protected constructor for any subclasses of this impl to pass up its // routing type. if (getRoutingType() != RoutableDto.NON_ROUTABLE_TYPE) { emitDefaultRoutingTypeConstructor(builder); emitProtectedConstructor(builder); } // If this DTO is allowed to be constructed on the server, we expose a // static factory method. A DTO is allowed to be constructed if it is a // ServerToClientDto, or if it is not a top level type (non-routable). if (DtoTemplate.implementsServerToClientDto(dtoInterface) || getRoutingType() == RoutableDto.NON_ROUTABLE_TYPE) { emitFactoryMethod(builder); } } private void emitProtectedConstructor(StringBuilder builder) { builder.append(" protected "); builder.append(getImplClassName()); builder.append("(int type) {\n super(type);\n"); builder.append(" }\n\n"); } private void emitReturn(Method method, String fieldName, StringBuilder builder) { if (isJsonArray(method.getReturnType())) { // Wrap the returned List in the server adapter. builder.append("("); builder.append(JSON_ARRAY); builder.append(") new "); builder.append(JSON_ARRAY_ADAPTER); builder.append("("); builder.append(fieldName); builder.append(")"); } else if (isJsonStringMap(method.getReturnType())) { // Wrap the JsonArray. builder.append("("); builder.append(JSON_MAP); builder.append(") new "); builder.append(JSON_MAP_ADAPTER); builder.append("("); builder.append(fieldName); builder.append(")"); } else { builder.append(fieldName); } } private void emitSetter(Method method, String implName, String fieldName, StringBuilder builder) { builder.append("\n public "); builder.append(implName); builder.append(" "); builder.append(getSetterName(fieldName)); builder.append("("); appendType(method.getGenericReturnType(), builder); builder.append(" v) {\n"); builder.append(" "); builder.append(getHasFieldName(fieldName)); builder.append(" = true;\n"); builder.append(" "); builder.append(fieldName); builder.append(" = "); builder.append("v;\n return this;\n }\n"); } /** * Emits an add method to add to a list. If the list is null, it is created. * * @param method a method with a list return type */ private void emitListAdd(Method method, String fieldName, StringBuilder builder) { builder.append("\n public void "); builder.append(getListAdderName(fieldName)); builder.append("("); builder.append(getTypeArgumentImplName((ParameterizedType) method.getGenericReturnType())); builder.append(" v) {\n "); builder.append(getEnsureName(fieldName)); builder.append("();\n "); builder.append(fieldName); builder.append(".add(v);\n"); builder.append(" }\n"); } /** * Emits a put method to put a value into a map. If the map is null, it is created. * * @param method a method with a map return value */ private void emitMapPut(Method method, String fieldName, StringBuilder builder) { builder.append("\n public void "); builder.append(getMapPutterName(fieldName)); builder.append("(String k, "); builder.append(getTypeArgumentImplName((ParameterizedType) method.getGenericReturnType())); builder.append(" v) {\n "); builder.append(getEnsureName(fieldName)); builder.append("();\n "); builder.append(fieldName); builder.append(".put(k, v);\n"); builder.append(" }\n"); } /** * Emits a method to clear a list or map. Clearing the collections ensures * that the collection is created. */ private void emitClear(String fieldName, StringBuilder builder) { builder.append("\n public void "); builder.append(getClearName(fieldName)); builder.append("() {\n "); builder.append(getEnsureName(fieldName)); builder.append("();\n "); builder.append(fieldName); builder.append(".clear();\n"); builder.append(" }\n"); } /** * Emit a method that ensures a collection is initialized. */ private void emitEnsureCollection(Method method, String fieldName, StringBuilder builder) { builder.append("\n void "); builder.append(getEnsureName(fieldName)); builder.append("() {\n"); builder.append(" if (!"); builder.append(getHasFieldName(fieldName)); builder.append(") {\n "); builder.append(getSetterName(fieldName)); builder.append("("); builder.append(fieldName); builder.append(" != null ? "); builder.append(fieldName); builder.append(" : new "); builder.append(getImplName(method.getGenericReturnType(), false)); builder.append("());\n"); builder.append(" }\n"); builder.append(" }\n"); } /** * Appends a suitable type for the given type. For example, at minimum, this * will replace DTO interfaces with their implementation classes and JSON * collections with corresponding Java types. If a suitable type cannot be * determined, this will throw an exception. * * @param genericType the type as returned by e.g. * method.getGenericReturnType() */ private void appendType(Type genericType, final StringBuilder builder) { builder.append(getImplName(genericType, true)); } /** * In most cases we simply echo the return type and field name, except for * JsonArray<T>, which is special in the server impl case, since it must be * represented by a List<T> for Gson to correctly serialize/deserialize it. * * @param method The getter method. * @return String representation of what the field type should be, as well as * the assignment (initial value) to said field type, if any. */ private String getFieldTypeAndAssignment(Method method, String fieldName) { StringBuilder builder = new StringBuilder(); builder.append("protected "); appendType(method.getGenericReturnType(), builder); builder.append(" "); builder.append(fieldName); builder.append(";\n"); return builder.toString(); } /** * Returns the fully-qualified type name using Java concrete implementation * classes. * * For example, for JsonArray&lt;JsonStringMap&lt;Dto&gt;&gt;, this would * return "ArrayList&lt;Map&lt;String, DtoImpl&gt;&gt;". */ private String getImplName(Type type, boolean allowJreCollectionInterface) { Class<?> rawClass = getRawClass(type); String fqName = getFqParameterizedName(type); fqName = fqName.replaceAll(JsonArray.class.getCanonicalName(), ArrayList.class.getCanonicalName()); fqName = fqName.replaceAll(JsonStringMap.class.getCanonicalName() + "<", HashMap.class.getCanonicalName() + "<String, ");
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
true
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/com/google/collide/dtogen/DtoTemplate.java
api/src/main/java/com/google/collide/dtogen/DtoTemplate.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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 com.google.collide.dtogen; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import com.google.collide.dtogen.shared.ClientToServerDto; import com.google.collide.dtogen.shared.RoutableDto; import com.google.collide.dtogen.shared.RoutingType; import com.google.collide.dtogen.shared.ServerToClientDto; import com.google.common.base.Preconditions; /** * Base template for the generated output file that contains all the DTOs. * * Note that we generate client and server DTOs in separate runs of the * generator. * * The directionality of the DTOs only affects whether or not we expose methods * to construct an instance of the DTO. We need both client and server versions * of all DTOs (irrespective of direction), but you aren't allowed to construct * a new {@link ServerToClientDto} on the client. And similarly, you aren't * allowed to construct a {@link ClientToServerDto} on the server. * */ public class DtoTemplate { @SuppressWarnings("serial") public static class MalformedDtoInterfaceException extends RuntimeException { public MalformedDtoInterfaceException(String msg) { super(msg); } } // We keep a whitelist of allowed non-DTO generic types. static final Set<Class<?>> jreWhitelist = new HashSet<Class<?>>(Arrays.asList( new Class<?>[] {String.class, Integer.class, Double.class, Float.class, Boolean.class})); private final List<DtoImpl> dtoInterfaces = new ArrayList<DtoImpl>(); private final String packageName; private final String className; private final boolean isServerType; private final String apiHash; /** * @return whether or not the specified interface implements * {@link ClientToServerDto}. */ static boolean implementsClientToServerDto(Class<?> i) { return implementsInterface(i, ClientToServerDto.class); } /** * @return whether or not the specified interface implements * {@link ServerToClientDto}. */ static boolean implementsServerToClientDto(Class<?> i) { return implementsInterface(i, ServerToClientDto.class); } /** * Walks the superinterface hierarchy to determine if a Class implements some * target interface transitively. */ static boolean implementsInterface(Class<?> i, Class<?> target) { if (i.equals(target)) { return true; } boolean rtn = false; Class<?>[] superInterfaces = i.getInterfaces(); for (Class<?> superInterface : superInterfaces) { rtn = rtn || implementsInterface(superInterface, target); } return rtn; } /** * @return whether or not the specified interface implements * {@link RoutableDto}. */ private static boolean implementsRoutableDto(Class<?> i) { return implementsInterface(i, RoutableDto.class); } /** * Constructor. * * @param packageName The name of the package for the outer DTO class. * @param className The name of the outer DTO class. * @param isServerType Whether or not the DTO impls are client or server. */ DtoTemplate(String packageName, String className, String apiHash, boolean isServerType) { this.packageName = packageName; this.className = className; this.apiHash = apiHash; this.isServerType = isServerType; } /** * Adds an interface to the DtoTemplate for code generation. * * @param i */ public void addInterface(Class<?> i) { getDtoInterfaces().add(createDtoImplTemplate(i)); } /** * @return the dtoInterfaces */ public List<DtoImpl> getDtoInterfaces() { return dtoInterfaces; } /** * Returns the source code for a class that contains all the DTO impls for any * intefaces that were added via the {@link #addInterface(Class)} method. */ @Override public String toString() { StringBuilder builder = new StringBuilder(); emitPreamble(builder); emitClientFrontendApiVersion(builder); emitDtos(builder); emitPostamble(builder); return builder.toString(); } /** * Tests whether or not a given class is a part of our dto jar, and thus will * eventually have a generated Impl that is serializable (thus allowing it to * be a generic type). */ boolean isDtoInterface(Class<?> potentialDto) { for (DtoImpl dto : dtoInterfaces) { if (dto.getDtoInterface().equals(potentialDto)) { return true; } } return false; } /** * Will initialize the routing ID to be RoutableDto.INVALID_TYPE if it is not * routable. This is a small abuse of the intent of that value, but it allows * us to simply omit it from the routing type enumeration later. * * @param i the super interface type * @return a new DtoServerTemplate or a new DtoClientTemplate depending on * isServerImpl. */ private DtoImpl createDtoImplTemplate(Class<?> i) { int routingId = implementsRoutableDto(i) ? getRoutingId(i) : RoutableDto.NON_ROUTABLE_TYPE; return isServerType ? new DtoImplServerTemplate(this, routingId, i) : new DtoImplClientTemplate( this, routingId, i); } private void emitDtos(StringBuilder builder) { for (DtoImpl dto : getDtoInterfaces()) { builder.append(dto.serialize()); } } private void emitPostamble(StringBuilder builder) { builder.append("\n}"); } private void emitPreamble(StringBuilder builder) { builder.append("// GENERATED SOURCE. DO NOT EDIT.\npackage "); builder.append(packageName); builder.append(";\n\n"); if (isServerType) { builder.append("import com.google.collide.dtogen.server.JsonSerializable;\n"); builder.append("\n"); builder.append("import com.google.gson.Gson;\n"); builder.append("import com.google.gson.GsonBuilder;\n"); builder.append("import com.google.gson.JsonArray;\n"); builder.append("import com.google.gson.JsonElement;\n"); builder.append("import com.google.gson.JsonNull;\n"); builder.append("import com.google.gson.JsonObject;\n"); builder.append("import com.google.gson.JsonParser;\n"); builder.append("import com.google.gson.JsonPrimitive;\n"); builder.append("\n"); // builder.append("import java.util.List;\n"); //unused builder.append("import java.util.Map;\n"); } builder.append("\n\n@SuppressWarnings({\"cast\""); if (isServerType) { builder.append(", \"unchecked\", \"rawtypes\""); } builder.append("})\n"); // Note that we always use fully qualified path names when referencing Types // so we need not add any import statements for anything. builder.append("public class "); builder.append(className); builder.append(" {\n\n"); if (isServerType) { builder.append(" private static final Gson gson = " + "new GsonBuilder().serializeNulls().create();\n\n"); } builder.append(" private "); builder.append(className); builder.append("() {}\n"); } /** * Emits a static variable that is the hash of all the classnames, methodnames, and return types * to be used as a version hash between client and server. */ private void emitClientFrontendApiVersion(StringBuilder builder) { builder.append("\n public static final String CLIENT_SERVER_PROTOCOL_HASH = \""); builder.append(getApiHash()); builder.append("\";\n"); } private String getApiHash() { return apiHash; } /** * Extracts the {@link RoutingType} annotation to derive the stable * routing type. */ private int getRoutingId(Class<?> i) { RoutingType routingTypeAnnotation = i.getAnnotation(RoutingType.class); Preconditions.checkNotNull(routingTypeAnnotation, "RoutingType annotation must be specified for all subclasses of RoutableDto. " + i.getName()); return routingTypeAnnotation.type(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/com/google/collide/dtogen/DtoImpl.java
api/src/main/java/com/google/collide/dtogen/DtoImpl.java
package com.google.collide.dtogen; import java.io.Serializable; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import com.google.collide.dtogen.DtoTemplate.MalformedDtoInterfaceException; import com.google.collide.dtogen.shared.CompactJsonDto; import com.google.collide.dtogen.shared.SerializationIndex; import com.google.collide.json.shared.JsonArray; import com.google.collide.json.shared.JsonStringMap; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; /** * Abstract base class for the source generating template for a single DTO. */ abstract class DtoImpl { // If routingType is RoutableDto.INVALID_TYPE, then we simply exclude it // from our routing table. private final int routingType; private final Class<?> dtoInterface; private final DtoTemplate enclosingTemplate; private final boolean compactJson; final String implClassName; private final List<Method> dtoMethods; DtoImpl(DtoTemplate enclosingTemplate, int routingType, Class<?> dtoInterface) { this.enclosingTemplate = enclosingTemplate; this.routingType = routingType; this.dtoInterface = dtoInterface; this.implClassName = dtoInterface.getSimpleName() + "Impl"; this.compactJson = DtoTemplate.implementsInterface(dtoInterface, CompactJsonDto.class); this.dtoMethods = ImmutableList.copyOf(calcDtoMethods()); } protected boolean isCompactJson() { return compactJson; } public Class<?> getDtoInterface() { return dtoInterface; } public DtoTemplate getEnclosingTemplate() { return enclosingTemplate; } public int getRoutingType() { return routingType; } protected String getFieldName(String methodName) { // TODO: Consier field name obfuscation for code savings on the // wire. For now just use a munging of the getter's name (strip get and // make first letter lower cased). String fieldName = methodName.replaceFirst("get", ""); fieldName = Character.toLowerCase(fieldName.charAt(0)) + fieldName.substring(1); return fieldName; } protected String getImplClassName() { return implClassName; } protected String getSetterName(String fieldName) { return "set" + getCamelCaseName(fieldName); } protected String getListAdderName(String fieldName) { return "add" + getCamelCaseName(fieldName); } protected String getMapPutterName(String fieldName) { return "put" + getCamelCaseName(fieldName); } protected String getClearName(String fieldName) { return "clear" + getCamelCaseName(fieldName); } protected String getEnsureName(String fieldName) { return "ensure" + getCamelCaseName(fieldName); } protected String getCamelCaseName(String fieldName) { return Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1); } /** * Our super interface may implement some other interface (or not). We need to * know because if it does then we need to directly extend said super * interfaces impl class. */ protected Class<?> getSuperInterface() { Class<?>[] superInterfaces = dtoInterface.getInterfaces(); if (superInterfaces.length==0) return null; if (superInterfaces.length>1){ for (Class<?> cls : superInterfaces){ if (!cls.equals(Serializable.class)) return cls; } } return superInterfaces[0]; } /** * We need not generate a field and method for any method present on a parent * interface that our interface may inherit from. We only care about the new * methods defined on our superInterface. */ protected boolean ignoreMethod(Method method) { if (method == null) { return true; } // Look at any interfaces our superInterface implements. Class<?>[] superInterfaces = getInterfaces(dtoInterface); List<Method> methodsToExclude = new ArrayList<Method>(); // Collect methods on parent interfaces for (Class<?> parent : superInterfaces) { for (Method m : parent.getMethods()) { methodsToExclude.add(m); } } for (Method m : methodsToExclude) { if (m.equals(method)) { return true; } } return false; } private Class<?>[] getInterfaces(Class<?> iface) { HashSet<Class<?>> all = new HashSet<>(); loadInterfaces(all, iface); return all.toArray(new Class<?>[all.size()]); } private void loadInterfaces(HashSet<Class<?>> all, Class<?> iface) { for (Class<?> cls : iface.getInterfaces()) { if (all.add(cls)) { loadInterfaces(all, cls); } } } /** * Tests whether or not a given generic type is allowed to be used as a * generic. */ protected static boolean isWhitelisted(Class<?> genericType) { return DtoTemplate.jreWhitelist.contains(genericType); } /** * Tests whether or not a given return type is a JsonArray. */ public static boolean isJsonArray(Class<?> returnType) { return returnType.equals(JsonArray.class); } /** * Tests whether or not a given return type is a JsonArray. */ public static boolean isJsonStringMap(Class<?> returnType) { return returnType.equals(JsonStringMap.class); } /** * Expands the type and its first generic parameter (which can also have a * first generic parameter (...)). * * For example, JsonArray&lt;JsonStringMap&lt;JsonArray&lt;SomeDto&gt;&gt;&gt; * would produce [JsonArray, JsonStringMap, JsonArray, SomeDto]. */ public static List<Type> expandType(Type curType) { List<Type> types = new ArrayList<Type>(); do { types.add(curType); if (curType instanceof ParameterizedType) { Type[] genericParamTypes = ((ParameterizedType) curType).getActualTypeArguments(); if (genericParamTypes.length != 1) { throw new IllegalStateException("Multiple type parameters are not supported" + "(neither are zero type parameters)"); } Type genericParamType = genericParamTypes[0]; if (genericParamType instanceof Class<?>) { Class<?> genericParamTypeClass = (Class<?>) genericParamType; if (isWhitelisted(genericParamTypeClass)) { assert genericParamTypeClass.equals(String.class) : "For JSON serialization there can be only strings or DTO types. " + "Please ping smok@ if you see this assert happening."; } } curType = genericParamType; } else { if (curType instanceof Class) { Class<?> clazz = (Class<?>) curType; if (isJsonArray(clazz) || isJsonStringMap(clazz)) { throw new MalformedDtoInterfaceException( "JsonArray and JsonStringMap MUST have a generic type specified (and no... ? " + "doesn't cut it!)."); } } curType = null; } } while (curType != null); return types; } public static Class<?> getRawClass(Type type) { return (Class<?>) ((type instanceof ParameterizedType) ? ((ParameterizedType) type) .getRawType() : type); } String getRoutingTypeField() { return dtoInterface.getSimpleName().toUpperCase() + "_TYPE"; } /** * Returns public methods specified in DTO interface. * * <p>For compact DTO (see {@link CompactJsonDto}) methods are ordered * corresponding to {@link SerializationIndex} annotation. * * <p>Gaps in index sequence are filled with {@code null}s. */ protected List<Method> getDtoMethods() { return dtoMethods; } private Method[] calcDtoMethods() { if (!compactJson) { return dtoInterface.getMethods(); } Map<Integer, Method> methodsMap = new HashMap<Integer, Method>(); int maxIndex = 0; for (Method method : dtoInterface.getMethods()) { if (method.getName().equals("getType")) { continue; } SerializationIndex serializationIndex = method.getAnnotation(SerializationIndex.class); Preconditions.checkNotNull(serializationIndex, "Serialization index is not specified for %s in %s", method.getName(), dtoInterface.getSimpleName()); // "53" is the number of bits in JS integer. // This restriction will allow to add simple bit-field // "serialization-skipping-list" in the future. int index = serializationIndex.value(); Preconditions.checkState(index > 0 && index <= 53, "Serialization index out of range [1..53] for %s in %s", method.getName(), dtoInterface.getSimpleName()); Preconditions.checkState(!methodsMap.containsKey(index), "Duplicate serialization index for %s in %s", method.getName(), dtoInterface.getSimpleName()); maxIndex = Math.max(index, maxIndex); methodsMap.put(index, method); } Method[] result = new Method[maxIndex]; for (int index = 0; index < maxIndex; index++) { result[index] = methodsMap.get(index + 1); } return result; } protected boolean isLastMethod(Method method) { Preconditions.checkNotNull(method); return method == dtoMethods.get(dtoMethods.size() - 1); } public boolean isSerializable() { for (Class<?> cls : dtoInterface.getInterfaces()) if (cls.equals(Serializable.class)) return true; return false; } /** * @return String representing the source definition for the DTO impl as an * inner class. */ abstract String serialize(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/com/google/collide/dtogen/shared/SerializationIndex.java
api/src/main/java/com/google/collide/dtogen/shared/SerializationIndex.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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 com.google.collide.dtogen.shared; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation for specifying the index of field in serialized form. * * <p>Index must be a positive integer. * */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface SerializationIndex { int value(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/com/google/collide/dtogen/shared/CompactJsonDto.java
api/src/main/java/com/google/collide/dtogen/shared/CompactJsonDto.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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 com.google.collide.dtogen.shared; /** * Tag interface for DTOs that are serialized to compact * (non human readable) JSON. * * <p>Compact JSON has array as a root element. As a consequence GSON library * throws an exception when you try do deserialize JSON containing compact * object as a root. Deserialize using {@link com.google.gson.JsonElement} in * such cases. * * <p>Note: try to eliminate enums and boolean fields in DTO to get better * serialized form density. * */ public interface CompactJsonDto { }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/com/google/collide/dtogen/shared/RoutingType.java
api/src/main/java/com/google/collide/dtogen/shared/RoutingType.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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 com.google.collide.dtogen.shared; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation for associating a routing type with a dto interface. * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface RoutingType { int type(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/com/google/collide/dtogen/shared/ServerToClientDto.java
api/src/main/java/com/google/collide/dtogen/shared/ServerToClientDto.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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 com.google.collide.dtogen.shared; /** * Tag interface for DTOs that are meant to be sent from the server to the * client. * */ public interface ServerToClientDto extends RoutableDto { }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/com/google/collide/dtogen/shared/RoutableDto.java
api/src/main/java/com/google/collide/dtogen/shared/RoutableDto.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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 com.google.collide.dtogen.shared; /** * Base interface for all DTOs that adds a type tag for routing messages. * */ public interface RoutableDto { int NON_ROUTABLE_TYPE = -2; String TYPE_FIELD = "_type"; /** * Every DTO needs to report a type for the purposes of routing messages on * the client. */ int getType(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/com/google/collide/dtogen/shared/ClientToServerDto.java
api/src/main/java/com/google/collide/dtogen/shared/ClientToServerDto.java
// Copyright 2012 Google Inc. All Rights Reserved. // // 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 com.google.collide.dtogen.shared; /** * Tag interface for DTOs that are meant to be sent from the client to the * server. * */ public interface ClientToServerDto extends RoutableDto { }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/util/Box.java
api/src/main/java/org/waveprotocol/wave/model/util/Box.java
/** * 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 org.waveprotocol.wave.model.util; /** * Boxes a value. Mainly useful as a workaround for the finality requirement of * values in a java closure's scope. * * @author danilatos@google.com (Daniel Danilatos) * * @param <T> */ public class Box<T> { /** * Settable value. */ public T boxed; /** * Convenience factory method. */ public static <T> Box<T> create() { return new Box<T>(); } /** * Convenience factory method. */ public static <T> Box<T> create(T initial) { return new Box<T>(initial); } /** No initial value. */ public Box() { this(null); } /** * @param boxed initial value. */ public Box(T boxed) { this.boxed = boxed; } /** * Sets the boxed value to the given new value. */ public void set(T newVal) { this.boxed = newVal; } /** * @return the boxed value. */ public T get() { return this.boxed; } /** * Sets the boxed value to null. */ public void clear() { this.boxed = null; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/util/NumberPriorityQueue.java
api/src/main/java/org/waveprotocol/wave/model/util/NumberPriorityQueue.java
/** * 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 org.waveprotocol.wave.model.util; /** * A simple priority queue that using double rather than boxed Double * for efficiency. * * @author zdwang@google.com (David Wang) */ public interface NumberPriorityQueue { /** Number of items in the queue */ public int size(); /** Adds e to the back of the queue */ public boolean offer(double e); /** Peek at the head of queue */ public double peek(); /** Removes an item from the beginning of the queue */ public double poll(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/util/ReadableIntMap.java
api/src/main/java/org/waveprotocol/wave/model/util/ReadableIntMap.java
/** * 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 org.waveprotocol.wave.model.util; /** * A read-only interface to a map of ints to V. * * We define this in favor of using a java.util collections interface * so that we can write an optimized implementation for GWT. * * Null is not permitted as a key. * * Implementations must distinguish between null values and unset keys. * * @author ohler@google.com (Christian Ohler) * * @param <V> type of values in the map */ public interface ReadableIntMap<V> { // Maybe add a primitive hasEntry(key, value) that returns true if an // entry for the key exists AND the value is equal to value. /** * A procedure that accepts a key and the corresponding value from the map. */ public interface ProcV<V> { public void apply(int key, V value); } /** * Return the value associated with key. Must only be called if there * is one. */ V getExisting(int key); /** * Return the value associated with key, or defaultValue if there is none. */ V get(int key, V defaultValue); /** * Return the value associated with key, or null if there is none */ V get(int key); /** * Return true iff this map contains a value for the key key. */ boolean containsKey(int key); /** * Return true iff this map does not contain a value for any key. */ boolean isEmpty(); /** * Call the callback for every key-value pair in the map, in undefined * order. */ void each(ProcV<V> callback); /** * Count the number of key-value pairs in the map. * * Note: Depending on the underlying map implementation, this may be a * time-consuming operation. */ int countEntries(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/util/CollectionUtils.java
api/src/main/java/org/waveprotocol/wave/model/util/CollectionUtils.java
/** * 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 org.waveprotocol.wave.model.util; import org.waveprotocol.wave.model.util.ReadableStringMap.ProcV; import java.util.*; /** * Utilities related to StringMap, StringSet, and CollectionFactory. * * @author ohler@google.com (Christian Ohler) */ public class CollectionUtils { private CollectionUtils() { } public static final DataDomain<ReadableStringSet, StringSet> STRING_SET_DOMAIN = new DataDomain<ReadableStringSet, StringSet>() { @Override public void compose(StringSet target, ReadableStringSet changes, ReadableStringSet base) { target.clear(); target.addAll(base); target.addAll(changes); } @Override public StringSet empty() { return createStringSet(); } @Override public ReadableStringSet readOnlyView(StringSet modifiable) { return modifiable; } }; public static final DataDomain<ReadableStringMap<Object>, StringMap<Object>> STRING_MAP_DOMAIN = new DataDomain<ReadableStringMap<Object>, StringMap<Object>>() { @Override public void compose(StringMap<Object> target, ReadableStringMap<Object> changes, ReadableStringMap<Object> base) { target.clear(); target.putAll(base); target.putAll(changes); } @Override public StringMap<Object> empty() { return createStringMap(); } @Override public ReadableStringMap<Object> readOnlyView(StringMap<Object> modifiable) { return modifiable; } }; @SuppressWarnings("unchecked") public static <T> DataDomain<StringMap<T>, StringMap<T>> stringMapDomain() { return (DataDomain) STRING_MAP_DOMAIN; } @SuppressWarnings("unchecked") public static <T> DataDomain<Set<T>, Set<T>> hashSetDomain() { return (DataDomain) HASH_SET_DOMAIN; } public static final DataDomain<Set<Object>, Set<Object>> HASH_SET_DOMAIN = new DataDomain<Set<Object>, Set<Object>>() { @Override public void compose(Set<Object> target, Set<Object> changes, Set<Object> base) { target.clear(); target.addAll(changes); target.addAll(base); } @Override public Set<Object> empty() { return new HashSet<Object>(); } @Override public Set<Object> readOnlyView(Set<Object> modifiable) { return Collections.unmodifiableSet(modifiable); } }; /** * An adapter that turns a java.util.Map<String, V> into a StringMap<V>. * * @author ohler@google.com (Christian Ohler) * * @param <V> type of values in the map */ private static final class StringMapAdapter<V> implements StringMap<V> { private final Map<String, V> backend; private StringMapAdapter(Map<String, V> backend) { Preconditions.checkNotNull(backend, "Attempt to adapt a null map"); this.backend = backend; } @Override public void putAll(ReadableStringMap<V> pairsToAdd) { // TODO(ohler): check instanceof here and implement a fallback. backend.putAll(((StringMapAdapter<V>) pairsToAdd).backend); } @Override public void putAll(Map<String, V> sourceMap) { Preconditions.checkArgument(!sourceMap.containsKey(null), "Source map must not contain a null key"); backend.putAll(sourceMap); } @Override public void clear() { backend.clear(); } @Override public void put(String key, V value) { Preconditions.checkNotNull(key, "StringMap cannot contain null keys"); backend.put(key, value); } @Override public void remove(String key) { Preconditions.checkNotNull(key, "StringMap cannot contain null keys"); backend.remove(key); } @Override public boolean containsKey(String key) { Preconditions.checkNotNull(key, "StringMap cannot contain null keys"); return backend.containsKey(key); } @Override public V getExisting(String key) { Preconditions.checkNotNull(key, "StringMap cannot contain null keys"); if (!backend.containsKey(key)) { // Not using Preconditions.checkState to avoid unecessary string concatenation throw new IllegalStateException("getExisting: Key '" + key + "' is not in map"); } return backend.get(key); } @Override public V get(String key) { Preconditions.checkNotNull(key, "StringMap cannot contain null keys"); return backend.get(key); } @Override public V get(String key, V defaultValue) { Preconditions.checkNotNull(key, "StringMap cannot contain null keys"); if (backend.containsKey(key)) { return backend.get(key); } else { return defaultValue; } } @Override public boolean isEmpty() { return backend.isEmpty(); } @Override public void each(ProcV<? super V> callback) { for (Map.Entry<String, V> entry : backend.entrySet()) { callback.apply(entry.getKey(), entry.getValue()); } } @Override public void filter(EntryFilter<? super V> filter) { for (Iterator<Map.Entry<String, V>> iterator = backend.entrySet().iterator(); iterator.hasNext();) { Map.Entry<String, V> entry = iterator.next(); if (filter.apply(entry.getKey(), entry.getValue())) { // entry stays } else { iterator.remove(); } } } @Override public int countEntries() { return backend.size(); } @Override public String someKey() { return isEmpty() ? null : backend.keySet().iterator().next(); } @Override public ReadableStringSet keySet() { return new StringSetAdapter(backend.keySet()); } @Override public String toString() { return backend.toString(); } // NOTE(patcoleman): equals() and hashCode() should not be implemented in this adaptor, as // they are unsupported in the javascript collections. } /** * An adapter that turns a java.util.Map<Double, V> into a NumberMap<V>. * * @param <V> type of values in the map */ private static final class NumberMapAdapter<V> implements NumberMap<V> { private final Map<Double, V> backend; private NumberMapAdapter(Map<Double, V> backend) { Preconditions.checkNotNull(backend, "Attempt to adapt a null map"); this.backend = backend; } @Override public void putAll(ReadableNumberMap<V> pairsToAdd) { // TODO(ohler): check instanceof here and implement a fallback. backend.putAll(((NumberMapAdapter<V>) pairsToAdd).backend); } @Override public void putAll(Map<Double, V> sourceMap) { backend.putAll(sourceMap); } @Override public void clear() { backend.clear(); } @Override public void put(double key, V value) { backend.put(key, value); } @Override public void remove(double key) { backend.remove(key); } @Override public boolean containsKey(double key) { return backend.containsKey(key); } @Override public V getExisting(double key) { assert backend.containsKey(key); return backend.get(key); } @Override public V get(double key) { return backend.get(key); } @Override public V get(double key, V defaultValue) { if (backend.containsKey(key)) { return backend.get(key); } else { return defaultValue; } } @Override public boolean isEmpty() { return backend.isEmpty(); } @Override public void each(ProcV<V> callback) { for (Map.Entry<Double, V> entry : backend.entrySet()) { callback.apply(entry.getKey(), entry.getValue()); } } @Override public void filter(EntryFilter<V> filter) { for (Iterator<Map.Entry<Double, V>> iterator = backend.entrySet().iterator(); iterator.hasNext();) { Map.Entry<Double, V> entry = iterator.next(); if (filter.apply(entry.getKey(), entry.getValue())) { // entry stays } else { iterator.remove(); } } } @Override public int countEntries() { return backend.size(); } @Override public String toString() { return backend.toString(); } // NOTE(patcoleman): equals() and hashCode() should not be implemented in this adaptor, as // they are unsupported in the javascript collections. } /** * An adapter that turns a java.util.Map<Integer, V> into an IntMap<V>. * * @param <V> type of values in the map */ private static final class IntMapAdapter<V> implements IntMap<V> { private final Map<Integer, V> backend; private IntMapAdapter(Map<Integer, V> backend) { Preconditions.checkNotNull(backend, "Attempt to adapt a null map"); this.backend = backend; } @Override public void putAll(ReadableIntMap<V> pairsToAdd) { // TODO(ohler): check instanceof here and implement a fallback. backend.putAll(((IntMapAdapter<V>) pairsToAdd).backend); } @Override public void putAll(Map<Integer, V> sourceMap) { backend.putAll(sourceMap); } @Override public void clear() { backend.clear(); } @Override public void put(int key, V value) { backend.put(key, value); } @Override public void remove(int key) { backend.remove(key); } @Override public boolean containsKey(int key) { return backend.containsKey(key); } @Override public V getExisting(int key) { assert backend.containsKey(key); return backend.get(key); } @Override public V get(int key) { return backend.get(key); } @Override public V get(int key, V defaultValue) { if (backend.containsKey(key)) { return backend.get(key); } else { return defaultValue; } } @Override public boolean isEmpty() { return backend.isEmpty(); } @Override public void each(ProcV<V> callback) { for (Map.Entry<Integer, V> entry : backend.entrySet()) { callback.apply(entry.getKey(), entry.getValue()); } } @Override public void filter(EntryFilter<V> filter) { for (Iterator<Map.Entry<Integer, V>> iterator = backend.entrySet().iterator(); iterator.hasNext();) { Map.Entry<Integer, V> entry = iterator.next(); if (filter.apply(entry.getKey(), entry.getValue())) { // entry stays } else { iterator.remove(); } } } @Override public int countEntries() { return backend.size(); } @Override public String toString() { return backend.toString(); } // NOTE(patcoleman): equals() and hashCode() should not be implemented in this adaptor, as // they are unsupported in the javascript collections. } /** * An adapter that turns a java.util.Set<String> into a StringSet. * * @author ohler@google.com (Christian Ohler) */ private static class StringSetAdapter implements StringSet { private final Set<String> backend; private StringSetAdapter(Set<String> backend) { Preconditions.checkNotNull(backend, "Attempt to adapt a null set"); this.backend = backend; } @Override public void add(String s) { Preconditions.checkNotNull(s, "StringSet cannot contain null values"); backend.add(s); } @Override public void clear() { backend.clear(); } @Override public boolean contains(String s) { Preconditions.checkNotNull(s, "StringSet cannot contain null values"); return backend.contains(s); } @Override public void remove(String s) { Preconditions.checkNotNull(s, "StringSet cannot contain null values"); backend.remove(s); } @Override public boolean isEmpty() { return backend.isEmpty(); } @Override public void each(Proc callback) { for (String s : backend) { callback.apply(s); } } @Override public boolean isSubsetOf(Set<String> set) { return set.containsAll(backend); } @Override public boolean isSubsetOf(final ReadableStringSet other) { for (String s : backend) { if (!other.contains(s)) { return false; } } return true; } @Override public void addAll(ReadableStringSet set) { backend.addAll(((StringSetAdapter) set).backend); } @Override public void removeAll(ReadableStringSet set) { backend.removeAll(((StringSetAdapter) set).backend); } @Override public void filter(StringPredicate filter) { for (Iterator<String> iterator = backend.iterator(); iterator.hasNext();) { String x = iterator.next(); if (filter.apply(x)) { // entry stays } else { iterator.remove(); } } } @Override public String someElement() { return isEmpty() ? null : backend.iterator().next(); } @Override public String toString() { return backend.toString(); } @Override public int countEntries() { return backend.size(); } } /** * An adapter that wraps a {@link IdentityHashMap}, presenting it as an * {@link IdentitySet}. */ private static class IdentitySetAdapter<T> implements IdentitySet<T> { private final Map<T, T> backend = new IdentityHashMap<T, T>(); private IdentitySetAdapter() { } @Override public void add(T x) { Preconditions.checkNotNull(x, "IdentitySet cannot contain null values"); // Note: Boxed primitives, and String, are disallowed. There are special // purpose maps for those key types, and the equality semantics between // the boxed primitives of Javascript and Java are dubious at best. if (x instanceof String || x instanceof Integer || x instanceof Double || x instanceof Long || x instanceof Boolean) { throw new UnsupportedOperationException( "Should NOT use boxed primitives with IdentitySet"); } backend.put(x, x); } @Override public void clear() { backend.clear(); } @Override public boolean contains(T s) { Preconditions.checkNotNull(s, "IdentitySet cannot contain null values"); return backend.containsKey(s); } @Override public void remove(T s) { Preconditions.checkNotNull(s, "IdentitySet cannot contain null values"); backend.remove(s); } @Override public boolean isEmpty() { return backend.isEmpty(); } @Override public T someElement() { for (T e : backend.keySet()) { return e; } return null; } @Override public void each(Proc<? super T> procedure) { for (T s : backend.keySet()) { procedure.apply(s); } } @Override public String toString() { return backend.toString(); } @Override public int countEntries() { return backend.size(); } } private static class NumberPriorityQueueAdapter implements NumberPriorityQueue { private final Queue<Double> queue; private NumberPriorityQueueAdapter(Queue<Double> queue) { this.queue = queue; } @Override public boolean offer(double e) { return queue.offer(e); } @Override public double peek() { return queue.peek(); } @Override public double poll() { return queue.poll(); } @Override public int size() { return queue.size(); } } /** * An adapter that wraps a java.util.IdentityHashMap<K, V> into an * IdentityMap<K, V>. Note that this is a simple map, so 'identity' is defined * by the hashCode/equals of K instances. * * @param <K> type of keys in the map. * @param <V> type of values in the map */ private static class IdentityHashMapAdapter<K, V> implements IdentityMap<K, V> { private final Map<K, V> backend = new IdentityHashMap<K, V>(); private IdentityHashMapAdapter() { } @Override public V get(K key) { return backend.get(key); } @Override public boolean has(K key) { return backend.containsKey(key); } @Override public void put(K key, V value) { // Note: Boxed primitives, and String, are disallowed. See explanation in // IdentitySetAdapter. if (key instanceof String || key instanceof Integer || key instanceof Double || key instanceof Long || key instanceof Boolean) { throw new UnsupportedOperationException( "Should NOT use boxed primitives as key with identity map"); } backend.put(key, value); } @Override public void remove(K key) { removeAndReturn(key); } @Override public V removeAndReturn(K key) { return backend.remove(key); } @Override public void clear() { backend.clear(); } @Override public boolean isEmpty() { return backend.isEmpty(); } @Override public void each(ProcV<? super K, ? super V> proc) { for (Map.Entry<K, V> entry : backend.entrySet()) { proc.apply(entry.getKey(), entry.getValue()); } } @Override public <R> R reduce(R initial, Reduce<? super K, ? super V, R> proc) { R reduction = initial; for (Map.Entry<K, V> entry : backend.entrySet()) { reduction = proc.apply(reduction, entry.getKey(), entry.getValue()); } return reduction; } @Override public String toString() { return backend.toString(); } @Override public int countEntries() { return backend.size(); } // NOTE(patcoleman): equals() and hashCode() should not be implemented in this adaptor, as // they are unsupported in the javascript collections. } /** * An implementation of CollectionFactory based on java.util.HashSet and * java.util.HashMap. * * @author ohler@google.com (Christian Ohler) */ private static class HashCollectionFactory implements CollectionFactory { @Override public <V> StringMap<V> createStringMap() { return CollectionUtils.adaptStringMap(new HashMap<String, V>()); } @Override public <V> NumberMap<V> createNumberMap() { return CollectionUtils.adaptNumberMap(new HashMap<Double, V>()); } @Override public <V> IntMap<V> createIntMap() { return CollectionUtils.adaptIntMap(new HashMap<Integer, V>()); } @Override public StringSet createStringSet() { return CollectionUtils.adaptStringSet(new HashSet<String>()); } @Override public <T> IdentitySet<T> createIdentitySet() { return new IdentitySetAdapter<T>(); } @Override public <E> Queue<E> createQueue() { return new LinkedList<E>(); } @Override public NumberPriorityQueue createPriorityQueue() { return CollectionUtils.adaptNumberPriorityQueue(new PriorityQueue<Double>()); } @Override public <K, V> IdentityMap<K, V> createIdentityMap() { return new IdentityHashMapAdapter<K, V>(); } } private static final HashCollectionFactory HASH_COLLECTION_FACTORY = new HashCollectionFactory(); private static CollectionFactory defaultCollectionFactory = HASH_COLLECTION_FACTORY; /** * Implements a persistently empty string map that throws exceptions on * attempt to add keys. */ private static final class EmptyStringMap<V> implements StringMap<V> { @Override public void clear() { // Success as the map is already empty. } @Override public void filter(EntryFilter<? super V> filter) { } @Override public void put(String key, V value) { throw new UnsupportedOperationException(); } @Override public void putAll(ReadableStringMap<V> pairsToAdd) { throw new UnsupportedOperationException(); } @Override public void putAll(Map<String, V> sourceMap) { throw new UnsupportedOperationException(); } @Override public void remove(String key) { } @Override public boolean containsKey(String key) { return false; } @Override public int countEntries() { return 0; } @Override public void each(ProcV<? super V> callback) { } @Override public V get(String key, V defaultValue) { return null; } @Override public V get(String key) { return null; } @Override public V getExisting(String key) { throw new UnsupportedOperationException(); } @Override public boolean isEmpty() { return true; } @Override public String someKey() { return null; } @Override public ReadableStringSet keySet() { // TODO(danilatos/ohler): Implement an immutable EMPTY_SET return CollectionUtils.createStringSet(); } } private static final EmptyStringMap<Object> EMPTY_MAP = new EmptyStringMap<Object>(); private static final IdentityMap<Object, Object> EMPTY = new IdentityMap<Object, Object>() { @Override public void clear() { } @Override public int countEntries() { return 0; } @Override public void each(ProcV<? super Object, ? super Object> proc) { } @Override public Object get(Object key) { return null; } @Override public boolean has(Object key) { return false; } @Override public boolean isEmpty() { return true; } @Override public void put(Object key, Object value) { throw new UnsupportedOperationException(); } @Override public <R> R reduce(R initial, Reduce<? super Object, ? super Object, R> proc) { return initial; } @Override public void remove(Object key) { throw new UnsupportedOperationException(); } @Override public Object removeAndReturn(Object key) { throw new UnsupportedOperationException(); } }; // // Plain old collections. // /** * Creates an empty {@code HashSet}. */ public static <E> HashSet<E> newHashSet() { return new HashSet<E>(); } /** * Creates a {@code HashSet} instance containing the given elements. * * @param elements the elements that the set should contain * @return a newly created {@code HashSet} containing those elements. */ public static <E> HashSet<E> newHashSet(E... elements) { int capacity = Math.max((int) (elements.length / .75f) + 1, 16); HashSet<E> set = new HashSet<E>(capacity); Collections.addAll(set, elements); return set; } /** * Creates a {@code HashSet} instance containing the given elements. * * @param elements the elements that the set should contain * @return a newly created {@code HashSet} containing those elements. */ public static <E> HashSet<E> newHashSet(Collection<? extends E> elements) { return new HashSet<E>(elements); } /** * Creates an empty immutable set. * * @return a newly created set containing those elements. */ public static <E> Set<E> immutableSet() { // TODO(anorth): optimise to a truly immutable set. return Collections.unmodifiableSet(CollectionUtils.<E>newHashSet()); } /** * Creates an immutable set containing the given elements. * * @param elements the elements that the set should contain * @return a newly created set containing those elements. */ public static <E> Set<E> immutableSet(Collection<? extends E> elements) { // TODO(anorth): optimise to a truly immutable set. return Collections.unmodifiableSet(newHashSet(elements)); } /** * Creates an immutable set containing the given elements. * * @param elements the elements that the set should contain * @return a newly created set containing those elements. */ public static <E> Set<E> immutableSet(E... elements) { // TODO(anorth): optimise to a truly immutable set. return Collections.unmodifiableSet(newHashSet(elements)); } /** Creates an empty {@link HashMap}. */ public static <K, V> HashMap<K, V> newHashMap() { return new HashMap<K, V>(); } /** * Creates a {@link HashMap} containing the elements in the given map. */ public static <K, V> HashMap<K, V> newHashMap(Map<? extends K, ? extends V> map) { return new HashMap<K, V>(map); } /** Creates a new immutable map with one entry. */ public static <K, V> Map<K, V> immutableMap(K k1, V v1) { // TODO(anorth): optimise to a truly immutable map. return Collections.singletonMap(k1, v1); } /** Creates a new immutable map with the given entries. */ public static <K, V> Map<K, V> immutableMap(K k1, V v1, K k2, V v2) { Map<K, V> map = newHashMap(); map.put(k1, v1); map.put(k2, v2); return Collections.unmodifiableMap(map); } /** Creates a new, empty linked list. */ public static <T> LinkedList<T> newLinkedList() { return new LinkedList<T>(); } /** Creates a new linked list containing elements provided by an iterable. */ public static <T> LinkedList<T> newLinkedList(Iterable<? extends T> elements) { LinkedList<T> list = newLinkedList(); for (T e : elements) { list.add(e); } return list; } /** Creates a new linked list containing the provided elements. */ public static <T> LinkedList<T> newLinkedList(T... elements) { return newLinkedList(Arrays.asList(elements)); } /** Creates a new, empty array list. */ public static <T> ArrayList<T> newArrayList() { return new ArrayList<T>(); } /** Creates a new array list containing elements provided by an iterable. */ public static <T> ArrayList<T> newArrayList(Iterable<? extends T> elements) { ArrayList<T> list = newArrayList(); for (T e : elements) { list.add(e); } return list; } /** Creates a new array list containing the provided elements. */ public static <T> ArrayList<T> newArrayList(T... elements) { return newArrayList(Arrays.asList(elements)); } // // String-based collections. // /** * Sets the default collection factory. * * This is used in the GWT client initialization code to plug in the JSO-based * collection factory. There shouldn't be any need to call this from other * places. */ public static void setDefaultCollectionFactory(CollectionFactory f) { defaultCollectionFactory = f; } /** * Returns a CollectionFactory based on HashSet and HashMap from java.util. * * Note: getCollectionFactory() is probably a better choice. */ public static CollectionFactory getHashCollectionFactory() { return HASH_COLLECTION_FACTORY; } /** * Returns the default CollectionFactory. */ public static CollectionFactory getCollectionFactory() { return defaultCollectionFactory; } /** * Creates a new StringMap using the default collection factory. */ public static <V> StringMap<V> createStringMap() { return CollectionUtils.getCollectionFactory().createStringMap(); } /** * @returns an immutable empty map object. Always reuses the same object, does * not create new ones. */ @SuppressWarnings("unchecked") public static <V> StringMap<V> emptyMap() { return (StringMap<V>) EMPTY_MAP; } /** * @returns an immutable empty map object. Always reuses the same object, does * not create new ones. */ @SuppressWarnings("unchecked") public static <K, V> IdentityMap<K, V> emptyIdentityMap() { return (IdentityMap<K, V>) EMPTY; } /** * Creates a new NumberMap using the default collection factory. */ public static <V> NumberMap<V> createNumberMap() { return CollectionUtils.getCollectionFactory().createNumberMap(); } /** * Creates a new NumberMap using the default collection factory. */ public static <V> IntMap<V> createIntMap() { return CollectionUtils.getCollectionFactory().createIntMap(); } /** * Creates a new queue using the default collection factory. */ public static <V> Queue<V> createQueue() { return CollectionUtils.getCollectionFactory().createQueue(); } /** * Creates a new priority queue using the default collection factory. */ public static NumberPriorityQueue createPriorityQueue() { return CollectionUtils.getCollectionFactory().createPriorityQueue(); } /** * Creates a new IdentityMap using the default collection factory. */ public static <K, V> IdentityMap<K, V> createIdentityMap() { return CollectionUtils.getCollectionFactory().createIdentityMap(); } /** * Creates a new IdentitySet using the default collection factory. */ public static <V> IdentitySet<V> createIdentitySet() { return CollectionUtils.getCollectionFactory().createIdentitySet(); } /** * Creates a new, immutable, singleton IdentitySet. */ public static <V> ReadableIdentitySet<V> singleton(final V value) { Preconditions.checkNotNull(value, "Can not create singleton of null"); return new ReadableIdentitySet<V>() { @Override public boolean contains(V s) { // Note that == is used, not .equals(), because this is an identity set. return value == s; } @Override public int countEntries() { return 1; } @Override public void each(Proc<? super V> procedure) { procedure.apply(value); } @Override public V someElement() { return value; } @Override public boolean isEmpty() { return false; } }; } /** * Creates a new StringSet using the default collection factory. */ public static StringSet createStringSet() { return getCollectionFactory().createStringSet(); } public static <V> StringMap<V> copyStringMap(ReadableStringMap<V> m) { StringMap<V> copy = createStringMap(); copy.putAll(m); return copy; } public static StringSet copyStringSet(ReadableStringSet s) { StringSet copy = createStringSet(); copy.addAll(s); return copy; } /** * Adds all entries from the source map to the target map. * * @return the target map, for convenience */ public static <V, M extends Map<String, V>> M copyToJavaMap(ReadableStringMap<V> source, final M target) { source.each(new ProcV<V>() { @Override public void apply(String key, V value) { target.put(key, value); } }); return target; } /** * Adds all entries from the source map to the target map. NOTE(patcoleman): * please only call from assertions/testing code. Ideally everything should be * ignorant of the java.util.Map implementations as the collection API here * becomes more useful. * * @return java.util.Map version of our IdentityMap */ public static <K, V> Map<K, V> copyToJavaIdentityMapForTesting(IdentityMap<K, V> source) { final Map<K, V> result = new IdentityHashMap<K, V>(); source.each(new IdentityMap.ProcV<K, V>() { @Override public void apply(K key, V value) { result.put(key, value); } }); return result; } /** * Creates a new java set with the same contents as the source StringSet. */ public static <V> Map<String, V> newJavaMap(ReadableStringMap<V> source) { return copyToJavaMap(source, new HashMap<String, V>()); } /** * Adds all elements from the source set to the target collection. * * @return the target collection, for convenience */ public static <C extends Collection<String>> C copyToJavaCollection( ReadableStringSet source, final C target) { source.each(new StringSet.Proc() { @Override public void apply(String element) { target.add(element); } }); return target; } /** * Adds all values from the source map to the target collection. * * @return the target collection, for convenience */ public static <T, C extends Collection<T>> C copyValuesToJavaCollection( ReadableStringMap<T> source, final C target) { source.each(new ProcV<T>() { @Override public void apply(String key, T value) {
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
true
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/util/StringSet.java
api/src/main/java/org/waveprotocol/wave/model/util/StringSet.java
/** * 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 org.waveprotocol.wave.model.util; /** * A read-write interface to a set of strings. * * We define this in favor of using a standard Java collections interface * so that we can write an optimized implementation for GWT. * * Null is not permitted as a value. All methods, even {@link #contains(String)} * will throw an exception for null values. * * @author ohler@google.com (Christian Ohler) */ public interface StringSet extends ReadableStringSet { /** * A function that accepts a String and returns a boolean. */ public interface StringPredicate { boolean apply(String x); } /** * @param s must not be null * Adds s to the set. If s is already in the set, does nothing. */ void add(String s); /** * Removes s from the set. If s is not in the set, does nothing. */ void remove(String s); /** * Removes all strings from the set. */ void clear(); /** * Equivalent to calling add(s) for every s in stringsToAdd. */ void addAll(ReadableStringSet stringsToAdd); /** * Equivalent to calling remove(s) for every s in stringsToRemove. */ void removeAll(ReadableStringSet stringsToRemove); /** * Call the predicate for each entry in the set, in undefined order. * If the predicate returns false, the entry is removed from the * set; if it returns true, it remains. */ void filter(StringPredicate filter); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/util/ReadableIdentitySet.java
api/src/main/java/org/waveprotocol/wave/model/util/ReadableIdentitySet.java
/** * Copyright 2010 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 org.waveprotocol.wave.model.util; /** * A read only interface to a set of elements. * * This is used in favor of using a standard Java collections interface so that * Javascript-optimized implementations can be used in GWT code. * * Null is not permitted as a value. All methods, including * {@link #contains(Object)}, will reject null values. * * @author ohler@google.com (Christian Ohler) * @author hearnden@google.com (David Hearnden) */ public interface ReadableIdentitySet<T> { /** * A procedure that accepts an element from the set. */ public interface Proc<T> { void apply(T element); } /** @return true if and only if {@code s} is in this set. */ boolean contains(T s); /** @return true if and only if this set is empty. */ boolean isEmpty(); /** * @return some element in the set. If the set is empty, null is returned. */ T someElement(); /** * Calls a procedure with each element in this set, in undefined order. */ void each(Proc<? super T> procedure); /** * @return the size of this set. Note: Depending on the underlying * implementation, this may be a linear operation. */ int countEntries(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/util/ReadableStringMap.java
api/src/main/java/org/waveprotocol/wave/model/util/ReadableStringMap.java
/** * 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 org.waveprotocol.wave.model.util; /** * A read-only interface to a map of strings to V. * * We define this in favor of using a java.util collections interface so that we * can write an optimized implementation for GWT. * * Null is not permitted as a key. All methods, even * {@link #containsKey(String)} will reject null keys. * * Implementations must distinguish between null values and unset keys. * * @author ohler@google.com (Christian Ohler) * * @param <V> type of values in the map */ public interface ReadableStringMap<V> { // Maybe add a primitive hasEntry(key, value) that returns true if an // entry for the key exists AND the value is equal to value. /** * A procedure that accepts a key and the corresponding value from the map. */ public interface ProcV<V> { public void apply(String key, V value); } /** * Return the value associated with key. Must only be called if there * is one. */ V getExisting(String key); /** * Return the value associated with key, or defaultValue if there is none. */ V get(String key, V defaultValue); /** * Return the value associated with key, or null if there is none */ V get(String key); /** * Return true iff this map contains a value for the key key. */ boolean containsKey(String key); /** * @return some key in the map. If the map is empty, null is returned. */ String someKey(); /** * Return true iff this map does not contain a value for any key. */ boolean isEmpty(); /** * Call the callback for every key-value pair in the map, in undefined * order. */ void each(ProcV<? super V> callback); /** * Count the number of key-value pairs in the map. * * Note: Depending on the underlying map implementation, this may be a * time-consuming operation. */ int countEntries(); /** * @return a live, unmodifiable view of the keys, as a set. If the map is * modified while iterating over the key set, the result is undefined. */ ReadableStringSet keySet(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/util/ReadableStringSet.java
api/src/main/java/org/waveprotocol/wave/model/util/ReadableStringSet.java
/** * 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 org.waveprotocol.wave.model.util; import java.util.Set; /** * A read only interface to a set of strings. * * We define this in favor of using a standard Java collections interface so * that we can write an optimized implementation for GWT. * * Null is not permitted as an element. All methods, even {@link #contains(String)} * will reject null elements. * * @author ohler@google.com (Christian Ohler) */ public interface ReadableStringSet { /** * A procedure that accepts an element from the set. */ public interface Proc { void apply(String element); } /** * Returns true iff s is in the set. */ boolean contains(String s); /** * @return some element in the set. If the set is empty, null is returned. */ String someElement(); /** * Returns true iff the set is empty. */ boolean isEmpty(); /** * Call the callback for each element in the map, in undefined order. */ void each(Proc callback); /** * Returns true iff every element of this is also in other. */ boolean isSubsetOf(ReadableStringSet other); /** * Returns true iff every element of this is also in other. */ boolean isSubsetOf(Set<String> other); /** * Count the number of entries in the set. * * Note: Depending on the underlying map implementation, this may be a * time-consuming operation. */ int countEntries(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/util/DataDomain.java
api/src/main/java/org/waveprotocol/wave/model/util/DataDomain.java
/** * 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 org.waveprotocol.wave.model.util; /** * A typeclass-style interface for manipulating mutable data * * @author danilatos@google.com (Daniel Danilatos) * * @param <T> The data type (e.g. StringSet) * @param <R> A read-only version of the data type (e.g. ReadableStringSet). * If none is available, then this may be the same as <T>. */ public interface DataDomain<R, T extends R> { /** * @return a new empty instance of the data */ T empty(); /** * Updates {@code target} to be the result of combining {@code changes} onto * {@code base} * * @param target * @param changes * @param base */ void compose(T target, R changes, R base); /** * @param modifiable * @return optionally a read-only view of the modifiable data, to provide * runtime readonly guarantees. Otherwise just return the parameter. */ R readOnlyView(T modifiable); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/util/IdentitySet.java
api/src/main/java/org/waveprotocol/wave/model/util/IdentitySet.java
/** * 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 org.waveprotocol.wave.model.util; /** * A read-write interface to a set of elements. * * This is used in favor of using a standard Java collections interface so that * Javascript-optimized implementations can be used in GWT code. * * Consistent with {@link ReadableIdentitySet}, null is not permitted as a * value. All methods will reject null values. * */ public interface IdentitySet<T> extends ReadableIdentitySet<T> { /** * Adds that an element to this set it is it not already present. Otherwise, * does nothing. * * @param s element to add */ void add(T s); /** * Removes an element from this set if it is present. Otherwise, does nothing. * * @param s element to remove */ void remove(T s); /** * Removes all elements from this set. */ void clear(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/util/StringMap.java
api/src/main/java/org/waveprotocol/wave/model/util/StringMap.java
/** * 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 org.waveprotocol.wave.model.util; import java.util.Map; /** * A read-write interface to a map of strings to V. * * Null is not permitted as a key. All methods, even * {@link #containsKey(String)} will reject null keys. * * @param <V> type of values in the map */ public interface StringMap<V> extends ReadableStringMap<V> { /** * A function that accepts a key and the corresponding value from the map. */ // TODO(ohler): Rename to EntryPredicate. public interface EntryFilter<V> { boolean apply(String key, V value); } /** * Sets the value associated with key to value. * If key already has a value, replaces it. * @param key must not be null */ void put(String key, V value); /** * Removes the value associated with key. Does nothing if there is none. */ void remove(String key); /** * Equivalent to calling put(key, value) for every key-value pair in * pairsToAdd. * * TODO(ohler): Remove this requirement. * Any data structure making use of a CollectionsFactory must only pass * instances of ReadableStringMap created by that factory as the pairsToAdd * argument. That is, if the Factory only creates StringMaps of a certain * type, you can rely on the fact that this method will only be called with * StringMaps of that type. */ void putAll(ReadableStringMap<V> pairsToAdd); /** * The equivalent of calling put(key, value) for every key-value pair in * sourceMap. */ void putAll(Map<String, V> sourceMap); /** * Removes all key-value pairs from this map. */ void clear(); /** * Call the filter for each key-value pair in the map, in undefined * order. If the filter returns false, the pair is removed from the map; * if it returns true, it remains. */ void filter(EntryFilter<? super V> filter); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/util/IdentityMap.java
api/src/main/java/org/waveprotocol/wave/model/util/IdentityMap.java
/** * 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 org.waveprotocol.wave.model.util; /** * Fast object identity map, where key set collisions are based on object * identity. * * There are two implementations, one for web mode and one for hosted mode. * While not strictly necessary for the web mode implementation, the hosted mode * implementation requires that the user does NOT override Object's * implementation of hashCode() or equals() for their key type. (It is also good * to enforce this, just to avoid confusion). This requirement is not statically * enforced, but runtime exceptions will be thrown if a non-identity .equals() * collision occurs with keys in the hosted mode implementation. * * @author danilatos@google.com (Daniel Danilatos) * * @param <K> * Key type. Restrictions: Must NOT override Object's implementation of * hashCode() or equals() * @param <V> * Value type. */ public interface IdentityMap<K, V> { /** * A procedure that accepts a key and the corresponding item from the map and * does something with them. * * @see IdentityMap#each(ProcV) * @param <K> IdentityMap's key type * @param <V> IdentityMap's value type */ public interface ProcV<K, V> { /** The procedure */ public void apply(K key, V item); } /** * A function that accepts an accumulated value, a key and the corresponding * item from the map and returns the new accumulated value. * * @see IdentityMap#reduce(Object, Reduce) * @param <K> IdentityMap's key type * @param <V> IdentityMap's value type * @param <R> The type of the value being accumulated */ public interface Reduce<K, V, R> { /** The function */ public R apply(R soFar, K key, V item); } /** * @param key * @return true if a value indexed by the given key is in the map */ boolean has(K key); /** * @param key * @return The value with the given key, or null if not present */ V get(K key); /** * Put the value in the map at the given key. Note: Does not return the old * value. * * @param key * @param value */ void put(K key, V value); /** * Remove the value with the given key from the map. Note: does not return the * old value. * * @param key */ void remove(K key); /** * Same as {@link #remove(Object)}, but returns what was previously there, if * anything. * * @param key * @return what was previously there or null */ V removeAndReturn(K key); /** * Removes all entries from this map. */ void clear(); /** * Tests whether this map is empty. * * @return true if this map has no entries. */ boolean isEmpty(); /** * Ruby/prototype.js style iterating idiom, using a callback. Equivalent to a * for-each loop. TODO(danilatos): Implement break and through a la * prototype.js if needed. * * @param proc */ void each(ProcV<? super K, ? super V> proc); /** * Same as ruby/prototype reduce. Same as functional fold. Apply a function * to an accumulator and key/value in the map. The function returns the new * accumulated value. TODO(danilatos): Implement break and through a la * prototype.js if needed. * * @param initial * @param proc * @return The accumulated value * @param <R> The accumulating type */ <R> R reduce(R initial, Reduce<? super K, ? super V, R> proc); /** * Returns the number of entries in the map. * * Note: This may be a time-consuming operation. */ int countEntries(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/util/FuzzingBackOffGenerator.java
api/src/main/java/org/waveprotocol/wave/model/util/FuzzingBackOffGenerator.java
/** * 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 org.waveprotocol.wave.model.util; /** * Simiple fibonacci back off with fuzzing. This is important for reconnection so that * everyone doesn't retry at the same time. * * @author zdwang@google.com (David Wang) */ public class FuzzingBackOffGenerator { public static class BackOffParameters { public final int targetDelay; public final int minimumDelay; private BackOffParameters(int targetDelay, int minimumDelay) { this.targetDelay = targetDelay; this.minimumDelay = minimumDelay; } } /** Randomisation factor. Must be between 0 and 1. */ private final double randomisationFactor; /** The first time we back off. */ private final int initialBackOff; /** The max back off value, it'll be fuzzed. */ private final int maxBackOff; /** The next time we've backed off. */ private int nextBackOffTime; /** The current back off time. */ private int backOffTime; /** * @param initialBackOff Initial value to back off. This class does not interpret the meaning of * this value. must be > 0 * @param maxBackOff Max value to back off * @param randomisationFactor between 0 and 1 to control the range of randomness. */ public FuzzingBackOffGenerator(int initialBackOff, int maxBackOff, double randomisationFactor) { if (randomisationFactor < 0 || randomisationFactor > 1) { throw new IllegalArgumentException("randomisationFactor must be between 0 and 1. actual " + randomisationFactor); } if (initialBackOff <= 0) { throw new IllegalArgumentException("initialBackOff must be between 0 and 1. actual " + initialBackOff); } this.randomisationFactor = randomisationFactor; this.initialBackOff = initialBackOff; this.maxBackOff = maxBackOff; this.nextBackOffTime = initialBackOff; this.backOffTime = 0; } /** Gets the next back off time. Until maxBackOff is reached. */ public BackOffParameters next() { int ret = Math.min(nextBackOffTime, maxBackOff); nextBackOffTime += backOffTime; backOffTime = ret; int randomizeTime = (int) (backOffTime * (1.0 + (Math.random() * randomisationFactor))); int minAllowedTime = (int)Math.round(randomizeTime - backOffTime * randomisationFactor); return new BackOffParameters(randomizeTime, minAllowedTime); } /** * Resets the back off. */ public void reset() { nextBackOffTime = initialBackOff; backOffTime = 0; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/util/Pair.java
api/src/main/java/org/waveprotocol/wave/model/util/Pair.java
/** * 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 org.waveprotocol.wave.model.util; /** * An immutable ordered pair of typed objects. * * Essentially the same as com.google.common.base.Pair. * (we avoid external dependencies from model/) * * * * @param <A> Type of value 1 * @param <B> Type of value 2 */ public class Pair<A, B> { /** * Static constructor to save typing on generic arguments. */ public static <A, B> Pair<A, B> of(A a, B b) { return new Pair<A, B>(a, b); } /** * The first element of the pair; see also {@link #getFirst}. */ public final A first; /** * The second element of the pair; see also {@link #getSecond}. */ public final B second; /** * Pair constructor * * @param first Value 1 * @param second Value 2 */ public Pair(A first, B second) { this.first = first; this.second = second; } /** * Copy constructor * * @param pair Pair to shallow copy from */ public Pair(Pair<? extends A, ? extends B> pair) { first = pair.first; second = pair.second; } /** * Returns the first element of this pair; see also {@link #first}. */ public A getFirst() { return first; } /** * Returns the second element of this pair; see also {@link #second}. */ public B getSecond() { return second; } /** * {@inheritDoc} * * NOTE: Not safe to override this method, hence final. */ @Override public final boolean equals(Object o) { if (o == null) return false; if (o == this) return true; if (o instanceof Pair) { Pair<?,?> p = (Pair<?,?>) o; return (p.first == first || (first != null && first.equals(p.first))) && (p.second == second || (second != null && second.equals(p.second))); } return false; } /** * {@inheritDoc} * * NOTE: Not safe to override this method, hence final. */ @Override public final int hashCode() { return (first == null ? 0 : first.hashCode()) + 37 * (second == null ? 0 : second.hashCode()); } /** {@inheritDoc} */ @Override public String toString() { return "(" + String.valueOf(first) + "," + String.valueOf(second) + ")"; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/util/ReadableNumberMap.java
api/src/main/java/org/waveprotocol/wave/model/util/ReadableNumberMap.java
/** * Copyright 2010 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 org.waveprotocol.wave.model.util; /** * A read-only interface to a map of doubles to V. * * We define this in favor of using a java.util collections interface * so that we can write an optimized implementation for GWT. * * Null is not permitted as a key. * * Implementations must distinguish between null values and unset keys. * * @author ohler@google.com (Christian Ohler) * * @param <V> type of values in the map */ public interface ReadableNumberMap<V> { // Maybe add a primitive hasEntry(key, value) that returns true if an // entry for the key exists AND the value is equal to value. /** * A procedure that accepts a key and the corresponding value from the map. */ public interface ProcV<V> { public void apply(double key, V value); } /** * Return the value associated with key. Must only be called if there * is one. */ V getExisting(double key); /** * Return the value associated with key, or defaultValue if there is none. */ V get(double key, V defaultValue); /** * Return the value associated with key, or null if there is none */ V get(double key); /** * Return true iff this map contains a value for the key key. */ boolean containsKey(double key); /** * Return true iff this map does not contain a value for any key. */ boolean isEmpty(); /** * Call the callback for every key-value pair in the map, in undefined * order. */ void each(ProcV<V> callback); /** * Count the number of key-value pairs in the map. * * Note: Depending on the underlying map implementation, this may be a * time-consuming operation. */ int countEntries(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/util/CopyOnWriteSet.java
api/src/main/java/org/waveprotocol/wave/model/util/CopyOnWriteSet.java
/** * 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 org.waveprotocol.wave.model.util; import com.google.common.annotations.VisibleForTesting; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashSet; /** * A container implementation that uses copy-on-write semantics to ensure that it is * safe to mutate the set while iterating. The iterator semantics are * equivalent to iterating though a snapshot taking at the time of calling * {@link #iterator()}; however, a copy-on-write strategy is better suited for * infrequently-modified but frequently-iterated container. * * A minor optimization to copy-on-write is that the underlying container is only * copied if an iterator has previously been created for it. This means that, * during a single iteration over a set of size N, a sequence of M operations * only costs O(N + M) rather than O(NM) (i.e., the first mutation does the * O(N) copy, and subsequent mutations do direct O(1) operations until another * iterator is created). * * NOTE(user): This class is not synchronized. * */ public final class CopyOnWriteSet<T> implements Iterable<T> { /** Factory for blah. */ interface CollectionFactory { /** @return a copy of a collection. */ <T> Collection<T> copy(Collection<T> source); } private final static CollectionFactory HASH_SET = new CollectionFactory() { @Override public <T> Collection<T> copy(Collection<T> source) { // HACK(zdwang): We should use a light weight container that does // not assume order when we feel confident enough that no one // have implicit reliance on order of iteration. return new LinkedHashSet<T>(source); } }; private final static CollectionFactory LIST_SET = new CollectionFactory() { @Override public <T> Collection<T> copy(Collection<T> source) { return CollectionUtils.newArrayList(source); } }; /** Factory for the underlying collection object. */ private final CollectionFactory factory; /** The base collection. Initially refers to a shared empty collection. */ private Collection<T> contents = Collections.emptySet(); /** True iff a copy is to be made on the next mutation. */ private boolean stale = true; @VisibleForTesting CopyOnWriteSet(CollectionFactory factory) { this.factory = factory; } /** @return a new copy-on-write set, with the default implementation. */ public static <T> CopyOnWriteSet<T> create() { return createHashSet(); } /** @return a new copy-on-write set, backed by a hash set. */ public static <T> CopyOnWriteSet<T> createHashSet() { return new CopyOnWriteSet<T>(HASH_SET); } /** @return a new copy-on-write set, backed by an array list. */ public static <T> CopyOnWriteSet<T> createListSet() { return new CopyOnWriteSet<T>(LIST_SET); } /** * Replaces the current set with a copy of it. */ private void copy() { assert stale; contents = factory.copy(contents); stale = false; } /** * Adds an item to this set. * * @param o object to add * @return whether the container changed due to the addition */ public boolean add(T o) { if (!stale) { return contents.add(o); } else { if (!contains(o)) { copy(); return contents.add(o); } else { return false; } } } /** * Removes an item from this set. * * @param o object to remove * @return whether the container changed due to the removal */ public boolean remove(T o) { if (!stale) { return contents.remove(o); } else { if (contains(o)) { copy(); return contents.remove(o); } else { return false; } } } /** * Checks whether an object exists in this collection. * * @param o object to check for existence */ public boolean contains(T o) { return contents.contains(o); } @Override public Iterator<T> iterator() { stale = true; return contents.iterator(); } /** * Clears this collection. */ public void clear() { contents = Collections.emptySet(); stale = true; } /** * @return true if this collection is empty. */ public boolean isEmpty() { return contents.isEmpty(); } /** * @return the size of this collection. */ public int size() { return contents.size(); } @Override public String toString() { return contents.toString(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/util/Preconditions.java
api/src/main/java/org/waveprotocol/wave/model/util/Preconditions.java
/** * 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 org.waveprotocol.wave.model.util; import com.google.common.annotations.VisibleForTesting; import javax.annotation.Nullable; /** * Utility functions for checking preconditions and throwing appropriate * Exceptions. * * This class mostly mimics com.google.common.base.Preconditions but only * implement the parts we need. * (we avoid external dependencies from model/) * TODO(tobiast): Add tests for this class */ public final class Preconditions { private Preconditions() {} public static void checkElementIndex(int index, int size) { assert size >= 0; if (index < 0) { throw new IndexOutOfBoundsException("index (" + index + ") must not be negative"); } if (index >= size) { throw new IndexOutOfBoundsException( "index (" + index + ") must be less than size (" + size + ")"); } } public static void checkPositionIndex(int index, int size) { assert size >= 0; if (index < 0) { throw new IndexOutOfBoundsException("index (" + index + ") must not be negative"); } if (index > size) { throw new IndexOutOfBoundsException( "index (" + index + ") must not be greater than size (" + size + ")"); } } public static void checkPositionIndexesInRange(int rangeStart, int start, int end, int rangeEnd) { assert rangeStart >= 0; assert rangeEnd >= rangeStart; if (start < rangeStart) { throw new IndexOutOfBoundsException("start index (" + start + ") " + "must not be less than start of range (" + rangeStart + ")"); } if (end < start) { throw new IndexOutOfBoundsException( "end index (" + end + ") must not be less than start index (" + start + ")"); } if (end > rangeEnd) { throw new IndexOutOfBoundsException( "end index (" + end + ") must not be greater than end of range (" + rangeEnd + ")"); } } public static void checkPositionIndexes(int start, int end, int size) { checkPositionIndexesInRange(0, start, end, size); } /** * Note a failed null check. * * Useful when an explicit check was done separately, to avoid building up * the error message object or string unecessarily (if profiling reveals a * hotspot). * * @param errorMessage error message * @throws NullPointerException */ public static void nullPointer(Object errorMessage) { throw new NullPointerException("" + errorMessage); } /** * Note a failed null check. * * Useful when an explicit check was done separately, to avoid building up * the error message object or string unecessarily (if profiling reveals a * hotspot). * * @param errorMessageTemplate a template for the exception message. * The message is formed by replacing each {@code %s} * placeholder in the template with an argument. These are matched by * position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc. * Unmatched arguments will be appended to the formatted message in square * braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message * template. Arguments are converted to strings using * {@link String#valueOf(Object)}. Arguments can be null. */ public static void nullPointer(String errorMessageTemplate, @Nullable Object... errorMessageArgs) { throw new NullPointerException(format(errorMessageTemplate, errorMessageArgs)); } /** * Ensures that the specified object is not null. * * @param x the object to check * @param errorMessage error message * @return the object if it is not null * @throws NullPointerException if {@code x} is null */ public static <T> T checkNotNull(T x, Object errorMessage) { if (x == null) { throw new NullPointerException("" + errorMessage); } return x; } /** * Ensures that the specified object is not null. * * @param x the object to check * @param errorMessageTemplate a template for the exception message. * The message is formed by replacing each {@code %s} * placeholder in the template with an argument. These are matched by * position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc. * Unmatched arguments will be appended to the formatted message in square * braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message * template. Arguments are converted to strings using * {@link String#valueOf(Object)}. Arguments can be null. * @return the object if it is not null * @throws NullPointerException if {@code x} is null */ public static <T> T checkNotNull(T x, String errorMessageTemplate, @Nullable Object... errorMessageArgs) { if (x == null) { throw new NullPointerException(format(errorMessageTemplate, errorMessageArgs)); } return x; } /** * Note an illegal argument * * Useful when an explicit check was done separately, to avoid building up * the error message object or string unecessarily (if profiling reveals a * hotspot). * * @param errorMessage error message * @throws IllegalArgumentException */ public static void illegalArgument(Object errorMessage) { throw new IllegalArgumentException("" + errorMessage); } /** * Note an illegal argument * * Useful when an explicit check was done separately, to avoid building up * the error message object or string unecessarily (if profiling reveals a * hotspot). * * @param errorMessageTemplate a template for the exception message. * The message is formed by replacing each {@code %s} * placeholder in the template with an argument. These are matched by * position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc. * Unmatched arguments will be appended to the formatted message in square * braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message * template. Arguments are converted to strings using * {@link String#valueOf(Object)}. Arguments can be null. * @throws IllegalArgumentException */ public static void illegalArgument(String errorMessageTemplate, @Nullable Object... errorMessageArgs) { throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs)); } /** * Ensures the truth of an condition involving the a parameter to the * calling method, but not involving the state of the calling instance. * * @param condition a boolean expression * @param errorMessage error message * @throws IllegalArgumentException if {@code condition} is false */ public static void checkArgument(boolean condition, Object errorMessage) { if (!condition) { throw new IllegalArgumentException("" + errorMessage); } } /** * Ensures the truth of an condition involving the a parameter to the * calling method, but not involving the state of the calling instance. * * @param condition a boolean expression * @param errorMessageTemplate a template for the exception message. * The message is formed by replacing each {@code %s} * placeholder in the template with an argument. These are matched by * position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc. * Unmatched arguments will be appended to the formatted message in square * braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message * template. Arguments are converted to strings using * {@link String#valueOf(Object)}. Arguments can be null. * @throws IllegalArgumentException if {@code condition} is false */ public static void checkArgument(boolean condition, String errorMessageTemplate, @Nullable Object... errorMessageArgs) { if (!condition) { throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs)); } } /** * Note an illegal state. * * Useful when an explicit check was done separately, to avoid building up * the error message object or string unecessarily (if profiling reveals a * hotspot). * * @param errorMessage error message * @throws IllegalStateException */ public static void illegalState(Object errorMessage) { throw new IllegalStateException("" + errorMessage); } /** * Note an illegal state. * * Useful when an explicit check was done separately, to avoid building up * the error message object or string unecessarily (if profiling reveals a * hotspot). * * @param errorMessageTemplate a template for the exception message. * The message is formed by replacing each {@code %s} * placeholder in the template with an argument. These are matched by * position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc. * Unmatched arguments will be appended to the formatted message in square * braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message * template. Arguments are converted to strings using * {@link String#valueOf(Object)}. Arguments can be null. * @throws IllegalStateException */ public static void illegalState(String errorMessageTemplate, @Nullable Object... errorMessageArgs) { throw new IllegalStateException(format(errorMessageTemplate, errorMessageArgs)); } /** * Ensures the truth of an condition involving the state of the calling * instance, but not involving any parameters to the calling method. * * @param condition a boolean expression * @param errorMessage error message * @throws IllegalStateException if {@code condition} is false */ public static void checkState(boolean condition, Object errorMessage) { if (!condition) { throw new IllegalStateException("" + errorMessage); } } /** * Ensures the truth of an condition involving the state of the calling * instance, but not involving any parameters to the calling method. * * @param condition a boolean expression * @param errorMessageTemplate a template for the exception message. * The message is formed by replacing each {@code %s} * placeholder in the template with an argument. These are matched by * position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc. * Unmatched arguments will be appended to the formatted message in square * braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message * template. Arguments are converted to strings using * {@link String#valueOf(Object)}. Arguments can be null. * @throws IllegalStateException if {@code condition} is false */ public static void checkState(boolean condition, String errorMessageTemplate, @Nullable Object... errorMessageArgs) { if (!condition) { throw new IllegalStateException(format(errorMessageTemplate, errorMessageArgs)); } } /** * Substitutes each {@code %s} in {@code template} with an argument. These * are matched by position - the first {@code %s} gets {@code args[0]}, etc. * If there are more arguments than placeholders, the unmatched arguments will * be appended to the end of the formatted message in square braces. * * This method is copied verbatim from com.google.common.base.Preconditions. * * @param template a non-null string containing 0 or more {@code %s} * placeholders. * @param args the arguments to be substituted into the message * template. Arguments are converted to strings using * {@link String#valueOf(Object)}. Arguments can be null. */ @VisibleForTesting static String format(String template, @Nullable Object... args) { template = String.valueOf(template); // null -> "null" // start substituting the arguments into the '%s' placeholders StringBuilder builder = new StringBuilder( template.length() + 16 * args.length); int templateStart = 0; int i = 0; while (i < args.length) { int placeholderStart = template.indexOf("%s", templateStart); if (placeholderStart == -1) { break; } builder.append(template.substring(templateStart, placeholderStart)); builder.append(args[i++]); templateStart = placeholderStart + 2; } builder.append(template.substring(templateStart)); // if we run out of placeholders, append the extra args in square braces if (i < args.length) { builder.append(" ["); builder.append(args[i++]); while (i < args.length) { builder.append(", "); builder.append(args[i++]); } builder.append("]"); } return builder.toString(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/util/NumberMap.java
api/src/main/java/org/waveprotocol/wave/model/util/NumberMap.java
/** * 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 org.waveprotocol.wave.model.util; import java.util.Map; /** * A read-write interface to a map of Doubles to V. * * @param <V> type of values in the map * * @author zdwang@google.com (David Wang) */ public interface NumberMap<V> extends ReadableNumberMap<V> { /** * A function that accepts a key and the corresponding value from the map. * It should return true to keep the item in the map, false to remove. */ public interface EntryFilter<V> { public boolean apply(double key, V value); } /** * Sets the value associated with key to value. * If key already has a value, replaces it. */ void put(double key, V value); /** * Removes the value associated with key. Does nothing if there is none. */ void remove(double key); /** * Equivalent to calling put(key, value) for every key-value pair in * pairsToAdd. * * TODO(ohler): Remove this requirement. * Any data structure making use of a CollectionsFactory must only pass * instances of ReadableNumberMap created by that factory as the pairsToAdd * argument. That is, if the Factory only creates NumberMaps of a certain * type, you can rely on the fact that this method will only be called with * NumberMaps of that type. */ void putAll(ReadableNumberMap<V> pairsToAdd); /** * The equivalent of calling put(key, value) for every key-value pair in * sourceMap. */ void putAll(Map<Double, V> sourceMap); /** * Removes all key-value pairs from this map. */ void clear(); /** * Call the filter for each key-value pair in the map, in undefined * order. If the filter returns false, the pair is removed from the map; * if it returns true, it remains. */ void filter(EntryFilter<V> filter); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/util/CollectionFactory.java
api/src/main/java/org/waveprotocol/wave/model/util/CollectionFactory.java
/** * 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 org.waveprotocol.wave.model.util; import java.util.Queue; /** * A factory interface for creating the types of collections that we * have optimized JavaScript implementations for. */ public interface CollectionFactory { /** * Returns a new, empty StringMap. */ <V> StringMap<V> createStringMap(); /** * Returns a new, empty NumberMap. */ <V> NumberMap<V> createNumberMap(); /** * Returns a new, empty IntMap. */ <V> IntMap<V> createIntMap(); /** * Returns a new, empty StringSet. */ <V> StringSet createStringSet(); /** * Returns a new, empty IdentitySet. */ <T> IdentitySet<T> createIdentitySet(); /** * Returns a queue. */ <E> Queue<E> createQueue(); /** * Returns a priority queue. */ NumberPriorityQueue createPriorityQueue(); /** * Returns an identity map. */ <K, V> IdentityMap<K, V> createIdentityMap(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/util/IntMap.java
api/src/main/java/org/waveprotocol/wave/model/util/IntMap.java
/** * 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 org.waveprotocol.wave.model.util; import java.util.Map; /** * A read-write interface to a map of ints to V. * * @param <V> type of values in the map */ public interface IntMap<V> extends ReadableIntMap<V> { /** * A function that accepts a key and the corresponding value from the map. * It should return true to keep the item in the map, false to remove. */ public interface EntryFilter<V> { public boolean apply(int key, V value); } /** * Sets the value associated with key to value. * If key already has a value, replaces it. */ void put(int key, V value); /** * Removes the value associated with key. Does nothing if there is none. */ void remove(int key); /** * Equivalent to calling put(key, value) for every key-value pair in * pairsToAdd. * * TODO(ohler): Remove this requirement. * Any data structure making use of a CollectionsFactory must only pass * instances of ReadableIntMap created by that factory as the pairsToAdd * argument. That is, if the Factory only creates IntMaps of a certain * type, you can rely on the fact that this method will only be called with * intMaps of that type. */ void putAll(ReadableIntMap<V> pairsToAdd); /** * The equivalent of calling put(key, value) for every key-value pair in * sourceMap. */ void putAll(Map<Integer, V> sourceMap); /** * Removes all key-value pairs from this map. */ void clear(); /** * Call the filter for each key-value pair in the map, in undefined * order. If the filter returns false, the pair is removed from the map; * if it returns true, it remains. */ void filter(EntryFilter<V> filter); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/undo/UndoStack.java
api/src/main/java/org/waveprotocol/wave/model/undo/UndoStack.java
/** * 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 org.waveprotocol.wave.model.undo; import org.waveprotocol.wave.model.operation.OperationPair; import org.waveprotocol.wave.model.operation.TransformException; import org.waveprotocol.wave.model.util.Pair; import java.util.ArrayList; import java.util.List; import java.util.Stack; /** * An undo stack. * * TODO(user): This can be heavily optimised. * * * @param <T> The type of operations. */ final class UndoStack<T> { private static final class StackEntry<T> { final T op; List<T> nonUndoables = new ArrayList<T>(); StackEntry(T op) { this.op = op; } } // TODO(user): Switch to a Deque when GWT supports it. private final Stack<StackEntry<T>> stack = new Stack<StackEntry<T>>(); private final UndoManagerImpl.Algorithms<T> algorithms; UndoStack(UndoManagerImpl.Algorithms<T> algorithms) { this.algorithms = algorithms; } /** * Pushes an operation onto the undo stack. * * @param op the operation to push onto the undo stack */ void push(T op) { stack.push(new StackEntry<T>(op)); } /** * Pops an operation from the undo stack and returns the operation that * effects the undo and the transformed non-undoable operation. * * @return a pair containeng the operation that accomplishes the desired undo * and the transformed non-undoable operation */ Pair<T, T> pop() { if (stack.isEmpty()) { return null; } StackEntry<T> entry = stack.pop(); T op = algorithms.invert(entry.op); if (entry.nonUndoables.isEmpty()) { return new Pair<T, T>(op, null); } OperationPair<T> pair; try { pair = algorithms.transform(op, algorithms.compose(entry.nonUndoables)); } catch (TransformException e) { throw new IllegalStateException("invalid operation transformation encountered", e); } // TODO(user): Change the ternary expression to just stack.peek() after // switching from Stack to Deque. StackEntry<T> nextEntry = stack.isEmpty() ? null : stack.peek(); if (nextEntry != null) { nextEntry.nonUndoables.add(pair.serverOp()); } return new Pair<T, T>(pair.clientOp(), pair.serverOp()); } /** * Intermingles intervening operations that should not be undone. * * @param op the operation that should not be undone */ void nonUndoableOperation(T op) { if (!stack.isEmpty()) { stack.peek().nonUndoables.add(op); } } /** * Clear the stack. */ void clear() { stack.clear(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/undo/UndoManagerImpl.java
api/src/main/java/org/waveprotocol/wave/model/undo/UndoManagerImpl.java
/** * 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 org.waveprotocol.wave.model.undo; import org.waveprotocol.wave.model.operation.OperationPair; import org.waveprotocol.wave.model.operation.TransformException; import org.waveprotocol.wave.model.util.Pair; import java.util.ArrayList; import java.util.List; import java.util.Stack; /** * An undo manager implementation. * * * @param <T> The type of operations. */ public final class UndoManagerImpl<T> implements UndoManagerPlus<T> { /** * Algorithms required by the undo manager. * * @param <T> The type of operations. */ public interface Algorithms<T> { /** * Inverts the given operation. * * @param operation The operation to invert. * @return The inverse of the given operation. */ T invert(T operation); /** * Composes the given operations. * * @param operations The operations to compose. * @return The composition of the given operations. */ T compose(List<T> operations); /** * Transforms the given operations. * * @param op1 The first concurrent operation. * @param op2 The second concurrent operation. * @return The result of transforming the given operations. * @throws TransformException If there was a problem with the transform. */ OperationPair<T> transform(T op1, T op2) throws TransformException; } private static final class Checkpointer { // TODO(user): Switch to a Deque when GWT supports it. private final Stack<Integer> partitions = new Stack<Integer>(); private int lastPartition = 0; void checkpoint() { if (lastPartition > 0) { partitions.push(lastPartition); lastPartition = 0; } } int releaseCheckpoint() { if (lastPartition > 0) { int value = lastPartition; lastPartition = 0; return value; } if (partitions.isEmpty()) { return 0; } return partitions.pop(); } void increment() { ++lastPartition; } } private final Algorithms<T> algorithms; private final UndoStack<T> undoStack; private final UndoStack<T> redoStack; private final Checkpointer checkpointer = new Checkpointer(); public UndoManagerImpl(Algorithms<T> algorithms) { this.algorithms = algorithms; undoStack = new UndoStack<T>(algorithms); redoStack = new UndoStack<T>(algorithms); } @Override public void undoableOp(T op) { undoStack.push(op); checkpointer.increment(); redoStack.clear(); } @Override public void nonUndoableOp(T op) { undoStack.nonUndoableOperation(op); redoStack.nonUndoableOperation(op); } @Override public void checkpoint() { checkpointer.checkpoint(); } // TODO(user): This current implementation does more work than necessary. @Override public T undo() { Pair<T, T> undoPlus = undoPlus(); return undoPlus == null ? null : undoPlus.first; } // TODO(user): This current implementation does more work than necessary. @Override public T redo() { Pair<T, T> redoPlus = redoPlus(); return redoPlus == null ? null : redoPlus.first; } // TODO(user): This current implementation does more work than necessary. @Override public Pair<T, T> undoPlus() { int numToUndo = checkpointer.releaseCheckpoint(); if (numToUndo == 0) { return null; } List<T> operations = new ArrayList<T>(); for (int i = 0; i < numToUndo - 1; ++i) { operations.add(undoStack.pop().first); } Pair<T, T> ops = undoStack.pop(); operations.add(ops.first); T op = algorithms.compose(operations); redoStack.push(op); return new Pair<T, T>(op, ops.second); } @Override public Pair<T, T> redoPlus() { Pair<T, T> ops = redoStack.pop(); if (ops != null) { checkpointer.checkpoint(); undoStack.push(ops.first); checkpointer.increment(); } return ops; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/undo/UndoManagerPlus.java
api/src/main/java/org/waveprotocol/wave/model/undo/UndoManagerPlus.java
/** * Copyright 2010 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 org.waveprotocol.wave.model.undo; import org.waveprotocol.wave.model.util.Pair; /** * An <code>UndoManager</code> that provides versions of the undo and redo * methods which return more information. * * * @param <T> The type of operations. */ public interface UndoManagerPlus<T> extends UndoManager<T> { /** * Effects an undo. Returns null if there are no operations to undo. * * NOTE(user): Warning. This interface method may change. * * @return a pair containing the operation that will effect an undo and the * relevant transformed non-undoable operation (which may be null if * no such operation exists) * * NOTE(user): Returning null is probably slightly harder to use than * returning an operation that does nothing. */ Pair<T, T> undoPlus(); /** * Effects a redo. Returns null if there are no operations to redo. * * NOTE(user): Warning. This interface method may change. * * @return a pair containing the operation that will effect a redo and the * relevant transformed non-undoable operation (which may be null if * no such operation exists) * * NOTE(user): Returning null is probably slightly harder to use than * returning an operation that does nothing. */ Pair<T, T> redoPlus(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/undo/UndoManager.java
api/src/main/java/org/waveprotocol/wave/model/undo/UndoManager.java
/** * 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 org.waveprotocol.wave.model.undo; /** * An undo manager. * * * @param <T> The type of operations. */ public interface UndoManager<T> { /** * Places into the undo manager an operation that should be undone by undos. * * @param op the operation that should be undone by an appropriate undo */ void undoableOp(T op); /** * Places into the undo manager an operation that should not be undone by undos. * * @param op the operation that should not be undone by any undos */ void nonUndoableOp(T op); /** * Places an undo checkpoint. */ void checkpoint(); /** * Effects an undo. Returns null if there are no operations to undo. * * @return the operation that will effect an undo */ T undo(); /** * Effects a redo. Returns null if there are no operations to redo. * * @return the operation that will effect a redo */ T redo(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/operation/OperationPair.java
api/src/main/java/org/waveprotocol/wave/model/operation/OperationPair.java
/** * 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 org.waveprotocol.wave.model.operation; /** * A pair of operations. */ public final class OperationPair<O> { private final O clientOp; private final O serverOp; /** * Constructs an OperationPair from a client operation and a server operation. * * @param clientOp The client's operation. * @param serverOp The server's operation. */ public OperationPair(O clientOp, O serverOp) { this.clientOp = clientOp; this.serverOp = serverOp; } /** * @return The client's operation. */ public O clientOp() { return clientOp; } /** * @return The server's operation. */ public O serverOp() { return serverOp; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/operation/TransformException.java
api/src/main/java/org/waveprotocol/wave/model/operation/TransformException.java
/** * 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 org.waveprotocol.wave.model.operation; /** * An exception thrown to indicate that a problem was encountered while * performing a transformation. */ @SuppressWarnings("serial") public class TransformException extends Exception { /** * Constructs an exception with the specified detail message. * * @param message the detail message */ public TransformException(String message) { super(message); } /** * Constructs an exception with the specified cause. * * @param cause the cause */ public TransformException(Throwable cause) { super(cause); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/document/operation/Attributes.java
api/src/main/java/org/waveprotocol/wave/model/document/operation/Attributes.java
/** * 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 org.waveprotocol.wave.model.document.operation; import org.waveprotocol.wave.model.document.operation.impl.AttributesImpl; import org.waveprotocol.wave.model.document.operation.util.StateMap; /** * A set of attributes, implemented as a map from attribute names to attribute * values. The attributes in the map are sorted by their names, so that the set * obtained from entrySet() will allow you to easily iterate through the * attributes in sorted order. * * Implementations must be immutable. */ public interface Attributes extends StateMap { public static final AttributesImpl EMPTY_MAP = new AttributesImpl(); public Attributes updateWith(AttributesUpdate mutation); /** * Same as {@link #updateWith(AttributesUpdate)}, but the mutation does * not have to be compatible. This is useful when the mutation may * already be known to be incompatible, but we wish still to perform it. * * This is useful for validity checking code, for example. In general, * {@link #updateWith(AttributesUpdate)} should be used instead. * * @param mutation does not have to be compatible * @return a new updated map, based on the key to new-value pairs, ignoring * the old values. */ public Attributes updateWithNoCompatibilityCheck(AttributesUpdate mutation); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/document/operation/AttributesUpdate.java
api/src/main/java/org/waveprotocol/wave/model/document/operation/AttributesUpdate.java
/** * 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 org.waveprotocol.wave.model.document.operation; import org.waveprotocol.wave.model.document.operation.util.UpdateMap; import java.util.Collection; /** * A mutation of an <code>Attributes</code> object. This is a map from attribute * names to attribute values, indicating the attributes whose values should be * changed and what values they should be assigned, where a null value indicates * that the corresponding attribute should be removed. The entries in the map * are sorted by the attribute names, so that the set obtained from entrySet() * will allow you to easily iterate through the entries in sorted order. * * Implementations must be immutable. */ public interface AttributesUpdate extends UpdateMap { public AttributesUpdate composeWith(AttributesUpdate mutation); public AttributesUpdate exclude(Collection<String> keys); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/document/operation/AnnotationBoundaryMap.java
api/src/main/java/org/waveprotocol/wave/model/document/operation/AnnotationBoundaryMap.java
/** * 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 org.waveprotocol.wave.model.document.operation; /** * Information required by an annotation boundary operation component. * * Implementations must be immutable. The order of end keys and change keys * must be strictly monotonic (as verified by * DocOpAutomaton.checkAnnotationBoundary). */ public interface AnnotationBoundaryMap { int endSize(); String getEndKey(int endIndex); int changeSize(); String getChangeKey(int changeIndex); String getOldValue(int changeIndex); String getNewValue(int changeIndex); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/document/operation/DocInitializationCursor.java
api/src/main/java/org/waveprotocol/wave/model/document/operation/DocInitializationCursor.java
/** * 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 org.waveprotocol.wave.model.document.operation; /** * The callback interface used by DocInitialization's apply method. * * */ public interface DocInitializationCursor { void annotationBoundary(AnnotationBoundaryMap map); void characters(String chars); void elementStart(String type, Attributes attrs); void elementEnd(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/document/operation/DocOpCursor.java
api/src/main/java/org/waveprotocol/wave/model/document/operation/DocOpCursor.java
/** * 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 org.waveprotocol.wave.model.document.operation; /** * The callback interface used by DocOp's apply method. */ public interface DocOpCursor extends DocInitializationCursor { void retain(int itemCount); void deleteCharacters(String chars); void deleteElementStart(String type, Attributes attrs); void deleteElementEnd(); void replaceAttributes(Attributes oldAttrs, Attributes newAttrs); void updateAttributes(AttributesUpdate attrUpdate); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/document/operation/util/ImmutableStateMap.java
api/src/main/java/org/waveprotocol/wave/model/document/operation/util/ImmutableStateMap.java
/** * 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 org.waveprotocol.wave.model.document.operation.util; import org.waveprotocol.wave.model.document.operation.util.ImmutableUpdateMap.AttributeUpdate; import org.waveprotocol.wave.model.util.Preconditions; import java.util.*; public abstract class ImmutableStateMap<T extends ImmutableStateMap<T, U>, U extends UpdateMap> extends AbstractMap<String, String> { /** * A name-value pair representing an attribute. */ public static final class Attribute implements Entry<String,String> { // TODO: This class can be simplified greatly if // AbstractMap.SimpleImmutableEntry from Java 6 can be used. private final String name; private final String value; /** * Creates an attribute with a map entry representing an attribute * name-value pair. * * @param entry The attribute's name-value pair. */ public Attribute(Entry<String,String> entry) { this(entry.getKey(), entry.getValue()); } /** * Creates an attribute given a name-value pair. * * @param name The name of the attribute. * @param value The value of the attribute. */ public Attribute(String name, String value) { Preconditions.checkNotNull(name, "Null attribute name"); Preconditions.checkNotNull(value, "Null attribute value"); this.name = name; this.value = value; } @Override public String getKey() { return name; } @Override public String getValue() { return value; } @Override public String setValue(String value) { throw new UnsupportedOperationException("Attempt to modify an immutable map entry."); } @Override public boolean equals(Object o) { if (!(o instanceof Entry)) { return false; } Entry<?,?> entry = (Entry<?,?>) o; return ((name == null) ? entry.getKey() == null : name.equals(entry.getKey())) && ((value == null) ? entry.getValue() == null : value.equals(entry.getValue())); } @Override public int hashCode() { return ((name == null) ? 0 : name.hashCode()) ^ ((value == null) ? 0 : value.hashCode()); } @Override public String toString() { return "Attribute(" + name + "=" + value + ")"; } } private final List<Attribute> attributes; private final Set<Entry<String,String>> entrySet = new AbstractSet<Entry<String,String>>() { @Override public Iterator<Entry<String,String>> iterator() { return new Iterator<Entry<String,String>>() { private final Iterator<Attribute> iterator = attributes.iterator(); public boolean hasNext() { return iterator.hasNext(); } public Attribute next() { return iterator.next(); } public void remove() { throw new UnsupportedOperationException("Attempt to modify an immutable set."); } }; } @Override public int size() { return attributes.size(); } }; /** * Creates a new T object containing no T. */ public ImmutableStateMap() { attributes = Collections.emptyList(); } protected static final Comparator<Attribute> comparator = new Comparator<Attribute>() { @Override public int compare(Attribute a, Attribute b) { return a.name.compareTo(b.name); } }; /** * Constructs a new <code>T</code> object with the T * specified by the given mapping. * * @param map The mapping of attribute names to attribute values. */ public ImmutableStateMap(Map<String,String> map) { this.attributes = attributeListFromMap(map); } public ImmutableStateMap(String ... pairs) { Preconditions.checkArgument(pairs.length % 2 == 0, "Pairs must come in groups of two"); Map<String, String> map = new HashMap<String, String>(); for (int i = 0; i < pairs.length; i += 2) { Preconditions.checkNotNull(pairs[i], "Null key"); Preconditions.checkNotNull(pairs[i + 1], "Null value"); if (map.containsKey(pairs[i])) { Preconditions.illegalArgument("Duplicate key: " + pairs[i]); } map.put(pairs[i], pairs[i + 1]); } this.attributes = attributeListFromMap(map); } private List<Attribute> attributeListFromMap(Map<String, String> map) { ArrayList<Attribute> attributeList = new ArrayList<Attribute>(map.size()); for (Entry<String, String> entry : map.entrySet()) { if (entry.getKey() == null || entry.getValue() == null) { Preconditions.nullPointer("This map does not allow null keys or values"); } attributeList.add(new Attribute(entry)); } Collections.sort(attributeList, comparator); return attributeList; } protected ImmutableStateMap(List<Attribute> attributes) { this.attributes = attributes; } @Override public Set<Entry<String,String>> entrySet() { return entrySet; } /** * Returns a <code>T</code> object obtained by applying the update * specified by the <code>U</code> object into this * <code>T</code> object. * * @param attributeUpdate The update to apply. * @return A <code>T</code> object obtained by applying the given * update onto this object. */ public T updateWith(U attributeUpdate) { return updateWith(attributeUpdate, true); } public T updateWithNoCompatibilityCheck(U attributeUpdate) { return updateWith(attributeUpdate, false); } private T updateWith(U attributeUpdate, boolean checkCompatibility) { List<Attribute> newImmutableStateMap = new ArrayList<Attribute>(); Iterator<Attribute> iterator = attributes.iterator(); Attribute nextAttribute = iterator.hasNext() ? iterator.next() : null; // TODO: Have a slow path when the cast would fail. List<AttributeUpdate> updates = ((ImmutableUpdateMap<?,?>) attributeUpdate).updates; for (AttributeUpdate update : updates) { while (nextAttribute != null) { int comparison = update.name.compareTo(nextAttribute.name); if (comparison > 0) { newImmutableStateMap.add(nextAttribute); nextAttribute = iterator.hasNext() ? iterator.next() : null; } else if (comparison < 0) { if (checkCompatibility && update.oldValue != null) { Preconditions.illegalArgument( "Mismatched old value: attempt to update unset attribute with " + update); } break; } else if (comparison == 0) { if (checkCompatibility && !nextAttribute.value.equals(update.oldValue)) { Preconditions.illegalArgument( "Mismatched old value: attempt to update " + nextAttribute + " with " + update); } nextAttribute = iterator.hasNext() ? iterator.next() : null; break; } } if (update.newValue != null) { newImmutableStateMap.add(new Attribute(update.name, update.newValue)); } } if (nextAttribute != null) { newImmutableStateMap.add(nextAttribute); while (iterator.hasNext()) { newImmutableStateMap.add(iterator.next()); } } return createFromList(newImmutableStateMap); } protected abstract T createFromList(List<Attribute> attributes); public static void checkAttributesSorted(List<Attribute> attributes) { Attribute previous = null; for (Attribute a : attributes) { Preconditions.checkNotNull(a, "Null attribute"); assert a.name != null; assert a.value != null; if (previous != null && previous.name.compareTo(a.name) >= 0) { Preconditions.illegalArgument( "Attribute keys not strictly monotonic: " + previous.name + ", " + a.name); } previous = a; } } public static <T extends ImmutableStateMap<T, U>, U extends ImmutableUpdateMap<U, ?>> T updateWithoutCompatibilityCheck(T state, U update) { // the cast below is required to work with javac from OpenJDK 7 return ((ImmutableStateMap<T, U>) state).updateWith(update, false); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/document/operation/util/UpdateMap.java
api/src/main/java/org/waveprotocol/wave/model/document/operation/util/UpdateMap.java
/** * 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 org.waveprotocol.wave.model.document.operation.util; /** * Defines a reversible change on a map. */ public interface UpdateMap { int changeSize(); String getChangeKey(int changeIndex); String getOldValue(int changeIndex); String getNewValue(int changeIndex); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/document/operation/util/StateMap.java
api/src/main/java/org/waveprotocol/wave/model/document/operation/util/StateMap.java
/** * 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 org.waveprotocol.wave.model.document.operation.util; import java.util.Map; // This may change from extending java.util.Map public interface StateMap extends Map<String, String> { }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/document/operation/util/ImmutableUpdateMap.java
api/src/main/java/org/waveprotocol/wave/model/document/operation/util/ImmutableUpdateMap.java
/** * 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 org.waveprotocol.wave.model.document.operation.util; import org.waveprotocol.wave.model.util.Pair; import org.waveprotocol.wave.model.util.Preconditions; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; public abstract class ImmutableUpdateMap<T extends ImmutableUpdateMap<T, U>, U extends UpdateMap> implements UpdateMap { public static class AttributeUpdate { public final String name; final String oldValue; final String newValue; public AttributeUpdate(String name, String oldValue, String newValue) { Preconditions.checkNotNull(name, "Null name in AttributeUpdate"); this.name = name; this.oldValue = oldValue; this.newValue = newValue; } @Override public String toString() { return "[" + name + ": " + oldValue + " -> " + newValue + "]"; } } protected final List<AttributeUpdate> updates; @Override public int changeSize() { return updates.size(); } @Override public String getChangeKey(int i) { return updates.get(i).name; } @Override public String getOldValue(int i) { return updates.get(i).oldValue; } @Override public String getNewValue(int i) { return updates.get(i).newValue; } public ImmutableUpdateMap() { updates = Collections.emptyList(); } public ImmutableUpdateMap(String ... triples) { Preconditions.checkArgument(triples.length % 3 == 0, "Triples must come in groups of three"); ArrayList<AttributeUpdate> accu = new ArrayList<AttributeUpdate>(triples.length / 3); for (int i = 0; i < triples.length; i += 3) { Preconditions.checkNotNull(triples[i], "Null key"); accu.add(new AttributeUpdate(triples[i], triples[i + 1], triples[i + 2])); } Collections.sort(accu, comparator); for (int i = 1; i < accu.size(); i++) { int x = comparator.compare(accu.get(i - 1), accu.get(i)); if (x == 0) { throw new IllegalArgumentException("Duplicate key: " + accu.get(i).name); } assert x < 0; } updates = accu; } public ImmutableUpdateMap(Map<String, Pair<String, String>> updates) { this(tripletsFromMap(updates)); } private static String[] tripletsFromMap(Map<String, Pair<String, String>> updates) { String[] triplets = new String[updates.size() * 3]; int i = 0; for (Map.Entry<String, Pair<String, String>> e : updates.entrySet()) { triplets[i++] = e.getKey(); triplets[i++] = e.getValue().getFirst(); triplets[i++] = e.getValue().getSecond(); } return triplets; } protected ImmutableUpdateMap(List<AttributeUpdate> updates) { this.updates = updates; } public T exclude(Collection<String> names) { List<AttributeUpdate> newAttributes = new ArrayList<AttributeUpdate>(); for (AttributeUpdate update : updates) { if (!names.contains(update.name)) { newAttributes.add(update); } } return createFromList(newAttributes); } protected static final Comparator<AttributeUpdate> comparator = new Comparator<AttributeUpdate>() { @Override public int compare(AttributeUpdate a, AttributeUpdate b) { return a.name.compareTo(b.name); } }; public T composeWith(U mutation) { List<AttributeUpdate> newAttributes = new ArrayList<AttributeUpdate>(); Iterator<AttributeUpdate> iterator = updates.iterator(); AttributeUpdate nextAttribute = iterator.hasNext() ? iterator.next() : null; // TODO: Have a slow path when the cast would fail. List<AttributeUpdate> mutationAttributes = ((ImmutableUpdateMap<?,?>) mutation).updates; loop: for (AttributeUpdate attribute : mutationAttributes) { while (nextAttribute != null) { int comparison = comparator.compare(attribute, nextAttribute); if (comparison < 0) { break; } else if (comparison > 0) { newAttributes.add(nextAttribute); nextAttribute = iterator.hasNext() ? iterator.next() : null; } else { if (!areEqual(nextAttribute.newValue, attribute.oldValue)) { Preconditions.illegalArgument( "Mismatched old value: attempt to update " + nextAttribute + " with " + attribute); } newAttributes.add(new AttributeUpdate(attribute.name, nextAttribute.oldValue, attribute.newValue)); nextAttribute = iterator.hasNext() ? iterator.next() : null; continue loop; } } newAttributes.add(attribute); } if (nextAttribute != null) { newAttributes.add(nextAttribute); while (iterator.hasNext()) { newAttributes.add(iterator.next()); } } return createFromList(newAttributes); } protected abstract T createFromList(List<AttributeUpdate> attributes); // TODO: Is there a utility method for this somewhere? private boolean areEqual(Object a, Object b) { return (a == null) ? b == null : a.equals(b); } @Override public String toString() { return "Updates: " + updates; } public static void checkUpdatesSorted(List<AttributeUpdate> updates) { AttributeUpdate previous = null; for (AttributeUpdate u : updates) { Preconditions.checkNotNull(u, "Null attribute update"); assert u.name != null; if (previous != null && previous.name.compareTo(u.name) >= 0) { Preconditions.illegalArgument( "Attribute keys not strictly monotonic: " + previous.name + ", " + u.name); } previous = u; } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/model/document/operation/impl/AttributesImpl.java
api/src/main/java/org/waveprotocol/wave/model/document/operation/impl/AttributesImpl.java
/** * 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 org.waveprotocol.wave.model.document.operation.impl; import org.waveprotocol.wave.model.document.operation.Attributes; import org.waveprotocol.wave.model.document.operation.AttributesUpdate; import org.waveprotocol.wave.model.document.operation.util.ImmutableStateMap; import org.waveprotocol.wave.model.util.Preconditions; import org.waveprotocol.wave.model.util.ReadableStringMap; import org.waveprotocol.wave.model.util.ReadableStringMap.ProcV; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; public class AttributesImpl extends ImmutableStateMap<AttributesImpl, AttributesUpdate> implements Attributes { public AttributesImpl() { super(); } public AttributesImpl(Map<String, String> map) { super(map); } AttributesImpl(List<Attribute> attributes) { super(attributes); } public AttributesImpl(String... pairs) { super(pairs); } @Override protected AttributesImpl createFromList(List<Attribute> attributes) { return new AttributesImpl(attributes); } public static AttributesImpl fromSortedAttributes(List<Attribute> sortedAttributes) { checkAttributesSorted(sortedAttributes); return fromSortedAttributesUnchecked(sortedAttributes); } public static AttributesImpl fromSortedAttributesUnchecked(List<Attribute> sortedAttributes) { return new AttributesImpl(sortedAttributes); } public static AttributesImpl fromUnsortedAttributes(List<Attribute> unsortedAttributes) { List<Attribute> sorted = new ArrayList<Attribute>(unsortedAttributes); Collections.sort(sorted, comparator); // Use the checked variant here to check for duplicates. return fromSortedAttributes(sorted); } public static AttributesImpl fromStringMap(ReadableStringMap<String> stringMap) { final List<Attribute> attrs = new ArrayList<Attribute>(); stringMap.each(new ProcV<String>() { @Override public void apply(String key, String value) { attrs.add(new Attribute(key, value)); } }); return fromUnsortedAttributes(attrs); } /** * Sorts the input but doesn't check for duplicate names. */ public static AttributesImpl fromUnsortedAttributesUnchecked(List<Attribute> unsortedAttributes) { List<Attribute> sorted = new ArrayList<Attribute>(unsortedAttributes); Collections.sort(sorted, comparator); return fromSortedAttributesUnchecked(sorted); } /** * Sorts the input but doesn't check for duplicate names. * * @param pairs [name, value, name, value, ...] */ public static Attributes fromUnsortedPairsUnchecked(String ... pairs) { Preconditions.checkArgument(pairs.length % 2 == 0, "pairs.length must be even"); List<Attribute> attrs = new ArrayList<Attribute>(); for (int i = 0; i < pairs.length; i += 2) { attrs.add(new Attribute(pairs[i], pairs[i + 1])); } return fromUnsortedAttributesUnchecked(attrs); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/client/scheduler/Controller.java
api/src/main/java/org/waveprotocol/wave/client/scheduler/Controller.java
/** * 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 org.waveprotocol.wave.client.scheduler; import org.waveprotocol.wave.client.scheduler.Scheduler.Priority; import org.waveprotocol.wave.client.scheduler.Scheduler.Schedulable; import com.google.gwt.user.client.ui.Widget; /** * Something that can control the behaviour of the scheduler, and display * controls in the UI. * * The only control mechanism is the ability to enable or disable priority * levels, exposed by {@link #isRunnable(Priority)}. * * A controller is also notified when jobs are added and removed * */ public interface Controller { /** * Tells this controller a job was added. * * @param priority priority level * @param job the job */ void jobAdded(Priority priority, Schedulable job); /** * Tells this controller a job was removed. * * @param priority priority level * @param job the job */ void jobRemoved(Priority priority, Schedulable job); /** * Queries whether a priority level should be run or not. * * @param priority priority level * @return true if tasks in {@code priority} should be run; false if they * should not be run. */ boolean isRunnable(Priority priority); /** * Queries whether an individual job is to be suppressed when run at a specific priority. * This is independent of {@link #isRunnable(Priority)} * * @param priority * @param job * @return true if the job is to be suppressed */ boolean isSuppressed(Priority priority, Schedulable job); /** * Gets the view of this controller, if it has one. * * @return the controller's view, or {@code null} if there is no view. */ Widget asWidget(); /** * Controller implementation that does nothing. GWT optimizations should make * the cost of this implementation zero. */ public static final Controller NOOP = new Controller() { @Override public Widget asWidget() { return null; } @Override public void jobAdded(Priority priority, Schedulable job) { // Do nothing } @Override public void jobRemoved(Priority priority, Schedulable job) { // Do nothing } @Override public boolean isRunnable(Priority priority) { return true; } @Override public boolean isSuppressed(Priority priority, Schedulable job) { return false; } }; }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/client/scheduler/Scheduler.java
api/src/main/java/org/waveprotocol/wave/client/scheduler/Scheduler.java
/** * 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 org.waveprotocol.wave.client.scheduler; /** * Unified interface for scheduling asynchronous work. * * This interface provides a relatively compact set of methods and * sub-interfaces for dealing with the varying task scheduling concerns of the * single-threaded web client. The central idea is that scheduling the same job * more than once (where "same" is defined by object identity) overrides the * previous scheduling of that same job. * * Contract: * <ul> * <li>The exact order of execution of jobs with equal priorities and delays is * undefined</li> * <li>The semantics of scheduling a job with any of the schedule variant * methods below are identical to doing that but also calling cancel on it * first. For example, this means that the delay timer is reset, and the * priority is changed to the most recent value.</li> * <li>Scheduling a job is the same as scheduling a delayed job with a delay of * zero</li> * <li>Scheduling a repeating process with a positive delay but zero interval * is the same as scheduling a delayed process</li> * <li>Scheduling an incremental task is the same as scheduling a repeating * incremental task with a delay and interval both of zero</li> * <li>If the interval of a repeating job is too small and enough happens * before it is next up for being run so that it "deserves" to be run more than * once, the additional runs are dropped. They are not queued up or "owed" to it * in any way.</li> * </ul> * * NOTE(danilatos): There is currently no mechanism for jobs to be notified of * cancellation. The reason is that code written to depend on this sort of * functionality can suffer from difficult to debug race conditions. Ideally * code should be structured differently, so that it does not need this * facility. If it is really needed, it can also be implemented on top of this * scheduler fairly simply. We might revisit this decision if it later turns out * to be a much needed feature, in which case there are some easy changes to be * made here to allow it. * * @author danilatos@google.com (Daniel Danilatos) */ public interface Scheduler { /** * This is mainly used to listen to tasks that takes too long to run. * * @author zdwang@google.com (David Wang) */ public interface Listener { /** * The given job is taking too long. */ void onJobExecuted(Schedulable job, int timeSpent); } /** * Tag interface for things the scheduler accepts. */ public interface Schedulable { } /** * A unit of work to be run once. * * NOTE(danilatos): Same as GWT's Command * * The reason for the separate interface is to clarify its coupling to the * Scheduler interface, and the subtly different semantics involving * scheduling an already scheduled task. An additional reason is to provide * the common super interface for type-tagging reasons. */ public interface Task extends Schedulable { /** * Do the entirety of a small amount of work */ void execute(); } /** * A large task to be run incrementally as several units * * NOTE(danilatos): Same as GWT's IncrementalCommand. Often referred to as * "Process" for brevity. * * The reason for the separate interface is the same as for Task */ public interface IncrementalTask extends Schedulable { /** * Do a small unit of a large amount of work * * @return true if there is additional work, false if the task has completed */ boolean execute(); } /** * Priority levels at which tasks execute. These are not distinct merely by * their ordering, but each also has some distinct semantics that are * described below. */ public enum Priority { /** * Jobs that need to not be delayed any more than the single first timeout. * This means that critical tasks do not have the usual time-slice * semantics, and so there is not much point in scheduling an incremental * task at this priority. * * Almost nothing should be critical, because this risks slow script alerts. * Only tasks that depend on having exactly timeout delay for correctness * should be scheduled at this priority, and they should be small. */ CRITICAL, /** * High priority jobs whose correctness doesn't depend on eschewing the * possibility of extra delays. */ HIGH, /** * Between HIGH and LOW. */ MEDIUM, /** * Jobs to run at the lowest priority. Anything that should not hold up high * priority jobs. These jobs may also be additionally throttled when there * is user activity. */ LOW, /** * Do not use. * * NOTE(danilatos): This is a quick hack to allow suppression of individual * tasks for debugging purposes. It is not perfect and when someone has the * time they can do this "properly" without using this enum. * * Individual tasks may be disabled using the schedule knobs, and what this * actually does is cause them to always be scheduled at this super low * priority, which is also disabled by default when the knobs are used. That * is all - enabling this priority will flush the jobs, and it should then * be immediately disabled again to avoid strange behaviour. */ INTERNAL_SUPPRESS; } /** * Tell the scheduler that the user is active. This may cause it to throttle * low priority jobs for a short period. In IE, having excessive background * work can cause undesirable effects such as slow rendering and dropped keys * when typing. It might be that this method is not needed by non-IE * implementations, but should still be called. */ public void noteUserActivity(); /** * Schedule a task to run once at the given priority. * * @param task */ void schedule(Priority priority, Task task); /** * Schedule a process to run continuously at the given priority over a number * over separate time slices until completion. * * @param priority * @param process */ void schedule(Priority priority, IncrementalTask process); /** * Same as {@link #schedule(Priority, Task)}, but begin after a minimumTime * from now * * @param priority * @param task * @param minimumTime * Must be at least zero */ void scheduleDelayed(Priority priority, Task task, int minimumTime); /** * Same as {@link #schedule(Priority, IncrementalTask)}, but begin after a * minimumTime from now * * @param priority * @param process * @param minimumTime * Must be at least zero */ void scheduleDelayed( Priority priority, IncrementalTask process, int minimumTime ); /** * Schedule a process to run each unit of work once per given time interval, * starting at least from the given minimum time from now, until completion * * @param priority * @param process * @param minimumTime * Must be at least zero * @param interval * Must be at least zero */ void scheduleRepeating( Priority priority, IncrementalTask process, int minimumTime, int interval ); /** * Prevent the given job from running. Calling this on a job that is not * scheduled is a no-op. * * @param job */ void cancel(Schedulable job); /** * @param job * @return true if the given job is already scheduled */ boolean isScheduled(Schedulable job); /** * Adds a listener that may be interested in tasks that takes too long. * @param listener must not be null. */ void addListener(Listener listener); /** * Removes a listener. * @param listener no effect if it's not a known listener. */ void removeListener(Listener listener); /** * @return a short description. */ public String debugShortDescription(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/client/scheduler/SchedulerTimerService.java
api/src/main/java/org/waveprotocol/wave/client/scheduler/SchedulerTimerService.java
/** * 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 org.waveprotocol.wave.client.scheduler; import org.waveprotocol.wave.client.scheduler.Scheduler.IncrementalTask; import org.waveprotocol.wave.client.scheduler.Scheduler.Priority; import org.waveprotocol.wave.client.scheduler.Scheduler.Schedulable; import org.waveprotocol.wave.client.scheduler.Scheduler.Task; import com.google.gwt.core.client.Duration; import com.google.gwt.core.client.GWT; /** * Implements a TimerService using the Wave client's Scheduler package. * */ public class SchedulerTimerService implements TimerService { /** * Scheduler to use for scheduling tasks. */ private final Scheduler scheduler; /** * Priority jobs will be run at. */ private final Priority priority; /** * The start time of when SchedulerTimerService is created. */ private final double start = currentTimeMillis(); /** * Creates a new TimerService that runs all tasks at LOW priority by default. * * @param scheduler Scheduler to use. */ public SchedulerTimerService(Scheduler scheduler) { this(scheduler, Priority.LOW); } /** * Creates a new TimerService that runs tasks at the given priority. * * @param scheduler Scheduler to use. * @param priority Priority to run scheduled jobs at. */ public SchedulerTimerService(Scheduler scheduler, Priority priority) { this.scheduler = scheduler; this.priority = priority; } @Override public void schedule(Task task) { scheduler.schedule(priority, task); } @Override public void schedule(IncrementalTask process) { scheduler.schedule(priority, process); } @Override public void scheduleDelayed(Task task, int minimumTime) { scheduler.scheduleDelayed(priority, task, minimumTime); } @Override public void scheduleDelayed(IncrementalTask process, int minimumTime) { scheduler.scheduleDelayed(priority, process, minimumTime); } @Override public void scheduleRepeating(IncrementalTask process, int minimumTime, int interval) { scheduler.scheduleRepeating(priority, process, minimumTime, interval); } @Override public void cancel(Schedulable job) { scheduler.cancel(job); } @Override public boolean isScheduled(Schedulable job) { return scheduler.isScheduled(job); } @Override public int elapsedMillis() { return (int) (currentTimeMillis() - start); } @Override public double currentTimeMillis() { // Replace this with just Duration.currentTimeMillis() when it is itself // implemented with a GWT.isClient() check. return GWT.isClient() ? Duration.currentTimeMillis() : System.currentTimeMillis(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/client/scheduler/JobRegistry.java
api/src/main/java/org/waveprotocol/wave/client/scheduler/JobRegistry.java
/** * 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 org.waveprotocol.wave.client.scheduler; import org.waveprotocol.wave.client.scheduler.Scheduler.IncrementalTask; import org.waveprotocol.wave.client.scheduler.Scheduler.Priority; import org.waveprotocol.wave.client.scheduler.Scheduler.Schedulable; import org.waveprotocol.wave.client.scheduler.Scheduler.Task; import org.waveprotocol.wave.model.util.CollectionUtils; import org.waveprotocol.wave.model.util.IntMap; import java.util.LinkedList; import java.util.Queue; /** * Optimised data structure used by BrowserBackedScheduler to store currently running jobs. * * @author danilatos@google.com (Daniel Danilatos) */ public class JobRegistry { /** * Jobs at each priority. * * Array of priority ordinals to ordered maps (which JSO maps inherently are) * Each map is an ordered map of id to job. */ private final IntMap<Queue<Schedulable>> priorities = CollectionUtils.createIntMap(); /** Controller that collects job counts. */ private final Controller jobCounter; /** Used as part of a pair in a return value, to avoid creating an object */ private Schedulable returnJob; /** Number of jobs in the registry, to provide fast {@link #isEmpty()}. */ private int jobCount; /** * Creates a job registry. * * @param jobCounter counter of jobs */ public JobRegistry(Controller jobCounter) { this.jobCounter = jobCounter; for (Priority p : Priority.values()) { // TODO(zdwang): Use a fast LinkedList that doens't mak this class untestable. priorities.put(p.ordinal(), new LinkedList<Schedulable>()); } } /** * Add a job at the given priority * * @param priority * @param job */ public void add(Priority priority, Schedulable job) { assert job != null : "tried to add null job"; Queue<Schedulable> queue = priorities.get(priority.ordinal()); if (queue.remove(job)) { // Do nothing else queue.add(job); return; } else { queue.add(job); jobCount++; jobCounter.jobAdded(priority, job); } } /** * @param priority * @return the number of jobs at the given priority. */ public int numJobsAtPriority(Priority priority) { return priorities.get(priority.ordinal()).size(); } /** * Remove the first job for the given priority. * The job and its id can be retrieved by the various getRemoved* methods * (This is to avoid creating a pair object as a return value). * * @param priority */ public void removeFirst(Priority priority) { Queue<Schedulable> queue = priorities.get(priority.ordinal()); if (queue.isEmpty()) { returnJob = null; } else { returnJob = queue.poll(); jobCount--; jobCounter.jobRemoved(priority, returnJob); } } /** * Obliterate the job with the given priority and id. * Does NOT store information to be retrieved like {@link #removeFirst(Priority)} does. * * @param priority * @param id */ public void remove(Priority priority, Schedulable job) { if (priorities.get(priority.ordinal()).remove(job)) { jobCount--; jobCounter.jobRemoved(priority, job); } } /** * @return Job removed by {@link #removeFirst(Priority)} */ public Schedulable getRemovedJob() { return returnJob; } /** * @return Job removed by {@link #removeFirst(Priority)}, Cast to IncrementalTask. */ public IncrementalTask getRemovedJobAsProcess() { return (IncrementalTask) returnJob; } /** * @return Job removed by {@link #removeFirst(Priority)}, Cast to Task. */ public Task getRemovedJobAsTask() { return (Task) returnJob; } /** * Used for testing */ boolean debugIsClear() { for (Priority p : Priority.values()) { if (!priorities.get(p.ordinal()).isEmpty()) { assert jobCount > 0 : "Count 0 when: " + toString(); return false; } } assert jobCount == 0 : "Count non-zero when: " + toString(); return true; } /** * Tests if this registry has any jobs in it. * * @return true if this registry has no jobs, false otherwise. */ boolean isEmpty() { return jobCount == 0; } /** {@inheritDoc} */ @Override public String toString() { // NOTE(user): this causes "too much recursion" errors in Firefox? // return priorities.toSource(); // ... so we do explicit building instead :( StringBuilder result = new StringBuilder(); for (Priority p : Priority.values()) { result.append(" { priority: " + p + "; "); result.append(" jobs: " + priorities.get(p.ordinal()) + "; } "); } return result.toString(); } /** * @return short description */ public String debugShortDescription() { // NOTE(user): this causes "too much recursion" errors in Firefox? // return priorities.toSource(); // ... so we do explicit building instead :( StringBuilder result = new StringBuilder(); for (Priority p : Priority.values()) { result.append(" { priority: " + p + "; "); result.append(" jobs count: " + priorities.get(p.ordinal()).size() + "; } "); } return result.toString(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/client/scheduler/GwtSimpleTimer.java
api/src/main/java/org/waveprotocol/wave/client/scheduler/GwtSimpleTimer.java
/** * 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 org.waveprotocol.wave.client.scheduler; import com.google.gwt.core.client.Duration; import com.google.gwt.user.client.Timer; /** * GWT-based SimpleTimer implementation * * @author danilatos@google.com (Daniel Danilatos) */ public class GwtSimpleTimer implements SimpleTimer { /** * Factory for creating a GWT-based simple timer * * TODO(danilatos): Disallow creation of more than one timer, assuming its use * will be in the one and only scheduler? */ public static final Factory FACTORY = new Factory() { public SimpleTimer create(Runnable task) { return new GwtSimpleTimer(task); } }; /** The GWT timer used */ private final Timer timer = new Timer() { @Override public void run() { task.run(); } }; /** The task to schedule */ private final Runnable task; private GwtSimpleTimer(Runnable task) { this.task = task; } /** {@inheritDoc} */ public double getTime() { return Duration.currentTimeMillis(); } /** {@inheritDoc} */ public void schedule() { // NOTE(danilatos): 1 instead of 0, because of some assertion in GWT's Timer // TODO(danilatos): Consider directly using setTimeout and not // GWT's timer, or fixing GWT's timer? There are some browser-specific // tunings in their implementation, so it doesn't make sense to just // ignore it. timer.schedule(1); } /** {@inheritDoc} */ public void cancel() { timer.cancel(); } /** {@inheritDoc} */ public void schedule(double when) { int interval = (int) (when - getTime()); timer.schedule(interval >= 1 ? interval : 1); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/client/scheduler/DelayedJobRegistry.java
api/src/main/java/org/waveprotocol/wave/client/scheduler/DelayedJobRegistry.java
/** * 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 org.waveprotocol.wave.client.scheduler; import org.waveprotocol.wave.client.scheduler.Scheduler.Schedulable; import org.waveprotocol.wave.model.util.CollectionUtils; import org.waveprotocol.wave.model.util.NumberMap; import org.waveprotocol.wave.model.util.NumberPriorityQueue; import org.waveprotocol.wave.model.util.StringMap; /** * Data structure used by BrowserBackedScheduler to store information needed to * keep track of delayed jobs. * * Creates only a single object per delayed job. This could be further optimised * at the cost of some code cleanliness. * * @author danilatos@google.com (Daniel Danilatos) */ public class DelayedJobRegistry { /** * Array of unique times for scheduled jobs */ private final NumberPriorityQueue jobTimes = CollectionUtils.createPriorityQueue(); /** * Map of times to job ids */ private final NumberMap<String> delayedJobIds = CollectionUtils.createNumberMap(); /** * Map of job ids to info */ private final StringMap<TaskInfo> delayedJobs = CollectionUtils.<TaskInfo>createStringMap(); /** * Constructor */ public DelayedJobRegistry() { } /** * Schedule a delayed, optionally repeating job * * @param info */ public void addDelayedJob(TaskInfo info) { delayedJobs.put(info.id, info); addDelayedTime(info); } /** * Remove a job from the data structure * @param id */ public void removeDelayedJob(String id) { if (delayedJobs.containsKey(id)) { delayedJobIds.remove(delayedJobs.get(id).getNextExecuteTime()); delayedJobs.remove(id); } } /** * Will get the next due delayed job with respect to the provided "now" time. * Note that if many jobs are scheduled for that moment, they will have slightly * larger values (usually in the order of less than 0.1), but this is accounted * for and they will be returned. * * @param now */ public Schedulable getDueDelayedJob(double now) { while (jobTimes.size() > 0 && jobTimes.peek() <= now + 0.99) { double time = this.jobTimes.poll(); if (!delayedJobIds.containsKey(time)) { // job was probably removed continue; } String id = delayedJobIds.get(time); TaskInfo info = delayedJobs.get(id); Schedulable job = info.job; this.removeDelayedJob(id); return job; } // No due job return null; } /** * @param id * @return True if the job with the given id is scheduled as a delayed job */ public boolean has(String id) { return delayedJobs.containsKey(id); } /** * @return The next time that a delayed job is due to run, or -1 for no jobs */ public double getNextDueDelayedJobTime() { return jobTimes.size() > 0 ? jobTimes.peek() : -1; } /** * Adds a mapping from a time to a job to run at that time. * * @param info */ private void addDelayedTime(TaskInfo info) { // Find a unique time whose floor is still equal to the // given time. The chances that this strategy will result in // time growing by an entire millisecond is infinitesimal, and even // if it does, it just means that the job will be one millisecond late, // which is still much smaller than the granularity of setTimeout. while (delayedJobIds.containsKey(info.getNextExecuteTime())) { info.jitterNextExecuteTime(); } jobTimes.offer(info.getNextExecuteTime()); delayedJobIds.put(info.getNextExecuteTime(), info.id); } /** * Used for testing */ boolean debugIsClear() { // Not checking jobTimes being empty because it is lazily cleaned up. return delayedJobIds.isEmpty() && delayedJobs.isEmpty(); } /** {@inheritDoc} */ @Override public String toString() { return "DJR[jobTimes:" + jobTimes + ",delayedJobIds:" + delayedJobIds + ",delayedJobs:" + delayedJobs + "]"; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/client/scheduler/TaskInfo.java
api/src/main/java/org/waveprotocol/wave/client/scheduler/TaskInfo.java
/** * 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 org.waveprotocol.wave.client.scheduler; import org.waveprotocol.wave.client.scheduler.Scheduler.Priority; import org.waveprotocol.wave.client.scheduler.Scheduler.Schedulable; /** * Some information about a scheduled task. * Gives each a unique id, and also stores the priority. * * @author danilatos@google.com (Daniel Danilatos) */ final class TaskInfo { private static int nextId; final String id = Integer.toString(++nextId); final Priority priority; final double startTime; final double interval; final Schedulable job; private double nextExecuteTime; public TaskInfo(Priority p, Schedulable job) { this(p, 0, 0, job); } public TaskInfo(Priority p, double startTime, double interval, Schedulable job) { priority = p; this.startTime = startTime; this.interval = interval; this.nextExecuteTime = startTime; this.job = job; } @Override public String toString() { return "TaskInfo { id: " + id + "; priority: " + priority + "; startTime: " + startTime + "; interval: " + interval + "; nextExecuteTime: " + nextExecuteTime + " }"; } public double getNextExecuteTime() { return nextExecuteTime; } /** * Updates this task's next execution time, and returns true if it * should be delayed again, false otherwise. * * @param now the current time * @return true if this task should be delayed. */ public boolean calculateNextExecuteTime(double now) { // NOTE: >, not >= // A delayed process with an interval of zero is just a regular process // with a delayed start time, so there is no need to delay again. Then // it will no longer be special, just a regular process in the regular queue. if (interval > 0) { nextExecuteTime = Math.floor((now - startTime) / interval + 1) * interval + startTime; return true; } return false; } /** * Jitter the next execution in an attempt to create a unique next execution time for this task. * @return a new next execution time that is very close to the original execution time. */ public double jitterNextExecuteTime() { // Find a unique time whose floor is still equal to the // given time. The chances that this strategy will result in // time growing by an entire millisecond is infinitesimal, and even // if it does, it just means that the job will be one millisecond late, // which is still much smaller than the granularity of setTimeout. nextExecuteTime += Math.random() * 0.1; return nextExecuteTime; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/client/scheduler/BrowserBackedScheduler.java
api/src/main/java/org/waveprotocol/wave/client/scheduler/BrowserBackedScheduler.java
/** * 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 org.waveprotocol.wave.client.scheduler; import org.waveprotocol.wave.model.util.CollectionUtils; import org.waveprotocol.wave.model.util.CopyOnWriteSet; import org.waveprotocol.wave.model.util.IdentityMap; import org.waveprotocol.wave.model.util.IdentityMap.ProcV; import org.waveprotocol.wave.model.util.Preconditions; import com.google.gwt.user.client.ui.Widget; /** * Implementation of a scheduler using two optimised javascript object * data structures for the registry of jobs. * * @author danilatos@google.com (Daniel Danilatos) */ public class BrowserBackedScheduler implements Scheduler { private final SimpleTimer timer; private final Runnable runner = new Runnable() { public void run() { nextSliceRunTime = Double.MAX_VALUE; workSlice(timeSliceMillis); double next = getNextRunTime(); if (next == 0) { maybeScheduleSlice(); } else if (next > 0) { maybeScheduleSlice(next); } } }; /** Controller for enabling/disabling priority levels, showing job counts, etc. */ private final Controller controller; /** * Map of scheduled tasks to info about them */ // TODO(danilatos): Swap out this implementation with a JSO based map when not in // hosted mode, where hashCode() for reference-based equality is a perfect hash private final IdentityMap<Schedulable, TaskInfo> taskInfos = CollectionUtils.createIdentityMap(); /** * Simple registry of jobs that are scheduled to run at the next available * opportunity. * This class maintains the invariant that if a job exists in {@code jobs}, * then that job also exists in {@code taskInfos}. */ private final JobRegistry jobs; /** * More complicated registry of delayed & repeating jobs. When something is * due to be run, it is taken from here and added to the {@link #jobs} * variable for actual execution. * This class maintains the invariant that if a job exists in * {@code delayedjobs}, then that job also exists in {@code taskInfos}. */ private final DelayedJobRegistry delayedJobs = new DelayedJobRegistry(); /** * How long each work slice should go for */ private int timeSliceMillis = 100; /** * When the next work slice is scheduled to run. * 0 means a slice is already scheduled to run as soon as possible. * >0 means a slice is scheduled to run at some epoch time, which is hopefully in the future. */ private double nextSliceRunTime = Double.MAX_VALUE; /** * The list of listeners that are interested in tasks that takes too long. */ private final CopyOnWriteSet<Listener> listeners = CopyOnWriteSet.createListSet(); public BrowserBackedScheduler(SimpleTimer.Factory timerFactory) { this(timerFactory, Controller.NOOP); } /** * @param timerFactory */ public BrowserBackedScheduler(SimpleTimer.Factory timerFactory, Controller controller) { this.timer = timerFactory.create(runner); this.controller = controller; this.jobs = new JobRegistry(controller); } @Override public void schedule(Priority priority, Task task) { Preconditions.checkArgument(priority != Priority.INTERNAL_SUPPRESS, "Don't use internal level"); scheduleJob(priority, task); } @Override public void schedule(Priority priority, IncrementalTask process) { Preconditions.checkArgument(priority != Priority.INTERNAL_SUPPRESS, "Don't use internal level"); scheduleJob(priority, process); } /** * Type independent worker for equivalent overloaded methods */ private void scheduleJob(Priority priority, Schedulable job) { if (controller.isSuppressed(priority, job) && priority != Priority.INTERNAL_SUPPRESS) { scheduleJob(Priority.INTERNAL_SUPPRESS, job); return; } TaskInfo info = taskInfos.get(job); // Cancel job if already scheduled if (info != null) { // Optimisation: nothing's changed, just return. if (priority == info.priority) { return; } cancel(job); } info = createTask(priority, job); jobs.add(priority, job); maybeScheduleSlice(); } private TaskInfo createTask(Priority priority, Schedulable job) { TaskInfo info = new TaskInfo(priority, job); taskInfos.put(job, info); return info; } private TaskInfo createDelayedTask(Priority priority, Schedulable job, double startTime, double interval) { TaskInfo info = new TaskInfo(priority, startTime, interval, job); taskInfos.put(job, info); return info; } @Override public void scheduleDelayed(Priority priority, Task task, int minimumTime) { Preconditions.checkArgument(minimumTime >= 0, "Minimum time must be at least zero"); Preconditions.checkArgument(priority != Priority.INTERNAL_SUPPRESS, "Don't use internal level"); if (minimumTime == 0) { schedule(priority, task); } scheduleDelayedJob(priority, task, minimumTime, -1); } @Override public void scheduleDelayed(Priority priority, IncrementalTask process, int minimumTime) { scheduleRepeating(priority, process, minimumTime, 0); } @Override public void scheduleRepeating(Priority priority, IncrementalTask process, int minimumTime, int interval) { Preconditions.checkArgument(minimumTime >= 0, "Minimum time must be at least zero"); Preconditions.checkArgument(interval >= 0, "Interval must be at least zero"); Preconditions.checkArgument(priority != Priority.INTERNAL_SUPPRESS, "Don't use internal level"); if (interval == 0 && minimumTime == 0) { schedule(priority, process); } scheduleDelayedJob(priority, process, minimumTime, interval); } /** * Worker for the delayed & repeating methods * @param interval if -1, then not repeating */ private void scheduleDelayedJob(Priority priority, Schedulable job, int minimumTime, int interval) { if (controller.isSuppressed(priority, job) && priority != Priority.INTERNAL_SUPPRESS) { scheduleDelayedJob(Priority.INTERNAL_SUPPRESS, job, minimumTime, interval); return; } TaskInfo info = taskInfos.get(job); if (info != null) { cancel(job); } double now = timer.getTime(); double startTime = now + minimumTime; info = createDelayedTask(priority, job, startTime, interval); delayedJobs.addDelayedJob(info); maybeScheduleSlice(startTime); } @Override public void cancel(Schedulable command) { TaskInfo info = taskInfos.removeAndReturn(command); if (info != null) { jobs.remove(info.priority, command); delayedJobs.removeDelayedJob(info.id); if (taskInfos.isEmpty()) { unscheduleSlice(); } } } @Override public boolean isScheduled(Schedulable job) { return taskInfos.get(job) != null; } private boolean hasJob(Schedulable command) { return taskInfos.has(command); } @Override public void noteUserActivity() { // TODO Auto-generated method stub throw new UnsupportedOperationException("noteUserActivity"); } /** * Set the size of a work time slice before work is deferred again * @param millis */ public void setTimeSlice(int millis) { timeSliceMillis = millis; } private boolean hasTasks() { return !taskInfos.isEmpty(); } /** * Do a unit of work from the given priority * * @param priority * @return true if there are more work units left in the scheduler */ // TODO(danilatos): Unit test this method (maybe change to package private) private boolean workUnit(Priority priority, int maxMillis) { jobs.removeFirst(priority); Schedulable job = jobs.getRemovedJob(); if (job == null) { return false; } double start = timer.getTime(); if (job instanceof IncrementalTask) { boolean isFinished = !jobs.getRemovedJobAsProcess().execute(); if (isFinished) { // Remove all trace cancel(job); } else { TaskInfo task = taskInfos.get(job); // If the job has more work to do, we add it back into the job queue, unless it has has // already been cancelled during execution (which would imply !hasJob) if (task != null && hasJob(job)) { // if it is a repeating job, add it to a delay before we contiune if (task.calculateNextExecuteTime(start)) { delayedJobs.addDelayedJob(task); } else if (!delayedJobs.has(task.id)) { jobs.add(priority, job); } } } } else { Task task = jobs.getRemovedJobAsTask(); // Remove all trace. cancel(job); task.execute(); } int timeSpent = (int) ( timer.getTime() - start); // This will only be useful when debugging in deobfuscated mode. triggerOnJobExecuted(job, timeSpent); return hasTasks(); } /** * Try to execute all the jobs at the given priority. At least 1 job at the given * priority will be executed. * @param priority * @param maxMillis the max number of millisec we are allowed to execute one task before * reporting it for a task that's too slow. * @param endTime if we exceeded this time, then we should stop and return false. * @return true if there are more time left that we can use to execute other jobs. */ private boolean workAll(Priority priority, int maxMillis, double endTime) { if (controller.isRunnable(priority) && jobs.numJobsAtPriority(priority) != 0) { boolean moreWork; boolean moreTime; do { moreWork = workUnit(priority, maxMillis); // TODO(user): // Add the following: // // double duration = finish - start; // if (duration > MAX_DURATION_MS && Debug.errorClient().shouldLog()) { // Debug.errorClient().log("HIGH priority task took a whopping: " // + ((int) duration) + "ms to run"); // } // // after dependencies are cleaned up such that Debug does not depend on Scheduler, so that // Scheduler can depend on Debug without a cycle. moreTime = timer.getTime() < endTime; } while (moreWork && moreTime); return moreTime; } return true; } /** * Work for the specified period or until there is no more work to do, * whichever comes first * * @param maxMillis */ // TODO(danilatos): Unit test this method (maybe change to package private) private void workSlice(int maxMillis) { double now = timer.getTime(); if (controller.isRunnable(Priority.CRITICAL)) { // Always do all critical tasks in one go while (workUnit(Priority.CRITICAL, maxMillis)) {} } Schedulable delayedJob; while ((delayedJob = delayedJobs.getDueDelayedJob(now)) != null) { TaskInfo info = taskInfos.get(delayedJob); jobs.add(info.priority, delayedJob); } // // Run HIGH priority tasks to the exclusion of MEDIUM and LOW priority tasks. // Also, always run at least one unit of HIGH priority, regardless of how long the previous // CRITICAL tasks took. // double end = now + maxMillis; for (Priority p : Priority.values()) { if (!workAll(p, maxMillis, end)) { return; } } } /** * @return Next time that a work slice should be due (not necessarily currently scheduled) * -1 means nothing to run, 0 means run as soon as possible, and >0 means don't run until * that many ms have elapsed. */ private double getNextRunTime() { // If there are normal jobs waitin, run as soon as possible. // Otherwise, run when the next delayed job wants to run. if (!jobs.isEmpty()) { return 0; } else { return delayedJobs.getNextDueDelayedJobTime(); } } /** * Ensure a work slice is scheduled to run at the next available opportunity */ private void maybeScheduleSlice() { if (nextSliceRunTime > 0) { timer.schedule(); nextSliceRunTime = 0; } } /** * Ensure a work slice is scheduled to run no later than the given time * @param when System time in millis when a slice should run */ private void maybeScheduleSlice(double when) { if (nextSliceRunTime > when) { timer.schedule(when); nextSliceRunTime = when; } } /** * Don't run the next slice */ private void unscheduleSlice() { nextSliceRunTime = Double.MAX_VALUE; timer.cancel(); } /** Used for testing */ boolean debugIsClear() { return taskInfos.isEmpty() && jobs.debugIsClear() && delayedJobs.debugIsClear(); } @Override public String debugShortDescription() { return "Scheduler[num ids:" + taskInfos.countEntries() + ", jobs:" + jobs.debugShortDescription() + ", delayed: " + delayedJobs.toString() + "]"; } @Override public String toString() { return "Scheduler[ids:" + tasks() + ", jobs:" + jobs.toString() + ", delayed: " + delayedJobs.toString() + "]"; } private String tasks() { final StringBuilder b = new StringBuilder(); taskInfos.each(new ProcV<Schedulable, TaskInfo>() { @Override public void apply(Schedulable key, TaskInfo item) { b.append("{ task: " + item); b.append("; "); b.append("job: " + key + " } "); } }); return b.toString(); } /** * Gets a UI component for controlling this scheduler's priority levels. * * @return the knobs control, or {@code null} if there is no knobs panel. */ public Widget getController() { return controller.asWidget(); } private void triggerOnJobExecuted(Schedulable job, int timeSpent) { for (Listener l : listeners) { l.onJobExecuted(job, timeSpent); } } @Override public void addListener(Listener listener) { listeners.add(listener); } @Override public void removeListener(Listener listener) { listeners.remove(listener); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/client/scheduler/SchedulerInstance.java
api/src/main/java/org/waveprotocol/wave/client/scheduler/SchedulerInstance.java
/** * 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 org.waveprotocol.wave.client.scheduler; import com.google.common.annotations.VisibleForTesting; import org.waveprotocol.wave.client.scheduler.Scheduler.Priority; import com.google.gwt.user.client.ui.Widget; /** * Provides a single Scheduler instance for all of the Wave client. This is * only a temporary measure while we convert existing classes to use a * dependency injected Scheduler. * */ public class SchedulerInstance { private static BrowserBackedScheduler instance; private static TimerService low; private static TimerService high; private static TimerService medium; /** Inject a default BrowserBackedScheduler */ @VisibleForTesting public static void setSchedulerInstance(BrowserBackedScheduler instance) { SchedulerInstance.instance = instance; setDefaultTimerService(); } private static void setDefaultTimerService() { low = new SchedulerTimerService(instance, Priority.LOW); high = new SchedulerTimerService(instance, Priority.HIGH); medium = new SchedulerTimerService(instance, Priority.MEDIUM); } /** Initialise a default BrowserBackedScheduler if there wasn't one */ private static void init() { if (instance == null) { setSchedulerInstance(new BrowserBackedScheduler(GwtSimpleTimer.FACTORY, Controller.NOOP)); } } /** * @return A shared Scheduler instance. */ public static Scheduler get() { init(); return instance; } /** * @return A shared low-priority timer service based on the scheduler instance. */ public static TimerService getLowPriorityTimer() { init(); return low; } /** * @return A shared high-priority timer service based on the scheduler instance. */ public static TimerService getHighPriorityTimer() { init(); return high; } /** * @return A shared high-priority timer service based on the scheduler instance. */ public static TimerService getMediumPriorityTimer() { init(); return medium; } /** * @return a widget for displaying and controlling the singleton scheduler. */ public static Widget getController() { init(); return instance.getController(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/client/scheduler/TimerService.java
api/src/main/java/org/waveprotocol/wave/client/scheduler/TimerService.java
/** * 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 org.waveprotocol.wave.client.scheduler; import org.waveprotocol.wave.client.scheduler.Scheduler.IncrementalTask; import org.waveprotocol.wave.client.scheduler.Scheduler.Schedulable; import org.waveprotocol.wave.client.scheduler.Scheduler.Task; /** * An interface for setting up timers that makes testing easier. Production * implementation uses {@link org.waveprotocol.wave.client.scheduler.Scheduler} * package. This interface obeys the same contract as does the Scheduler * interface. * */ public interface TimerService { /** * Schedule a task to run once. * * @param task Task to schedule. */ void schedule(Task task); /** * Schedule a process to run continuously over a number of separate time * slices until completion. * * @param process Process to schedule */ void schedule(IncrementalTask process); /** * Same as {@link #schedule(Task)}, but begin after a minimumTime from now * * @param task Task to schedule * @param minimumTime Must be at least zero */ void scheduleDelayed(Task task, int minimumTime); /** * Same as {@link #schedule(IncrementalTask)}, but begin after a minimumTime * from now * * @param process Process to schedule * @param minimumTime Must be at least zero */ void scheduleDelayed(IncrementalTask process, int minimumTime); /** * Schedule a process to run each unit of work once per given time interval, * starting at least from the given minimum time from now, until completion * * @param process Process to schedule * @param minimumTime Must be at least zero * @param interval Must be at least zero */ void scheduleRepeating(IncrementalTask process, int minimumTime, int interval); /** * Prevent the given job from running. Calling this on a job that is not * scheduled is a no-op. * * @param job */ void cancel(Schedulable job); /** * @return whether the job was previously scheduled. */ boolean isScheduled(Schedulable job); /** * @return The number of millisecond elapsed since this service started. */ int elapsedMillis(); /** * @return The current clock time in milliseconds since the UNIX epoch. * Double is preferred to long due to inefficient long implementation in GWT. */ double currentTimeMillis(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/client/scheduler/SimpleTimer.java
api/src/main/java/org/waveprotocol/wave/client/scheduler/SimpleTimer.java
/** * 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 org.waveprotocol.wave.client.scheduler; /** * A simple timer that is associated with a specific task that may be * scheduled/cancelled. Because it is associated with a specific task, it may be * efficiently implemented to avoid unecessary object creation and other * overheads when scheduling. * * Rather than having the interface mandate mutability through a setter for the * runnable task, a factory interface is instead provided for most uses. * * @author danilatos@google.com (Daniel Danilatos) */ public interface SimpleTimer { /** * Factory to create a simple timer. */ public interface Factory { /** Factory method */ SimpleTimer create(Runnable runnable); } /** * @return The current time in millis, as a double */ double getTime(); /** * Run the task at the next available opportunity. Implicitly cancels any * other scheduling. */ void schedule(); /** * Run the task at the next available opportunity, but no earlier than the * given time. Implicitly cancels any other scheduling. * * @param when */ void schedule(double when); /** * Cancel any scheduled running of the task. */ void cancel(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/client/common/util/JsoView.java
api/src/main/java/org/waveprotocol/wave/client/common/util/JsoView.java
/** * Copyright 2010 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 org.waveprotocol.wave.client.common.util; import org.waveprotocol.wave.model.util.ReadableStringMap.ProcV; import com.google.gwt.core.client.JavaScriptObject; /** * Presents a raw, direct view on a javascript object. Useful for exposing * properties that are not possible to modify with existing APIs. Also used as a * backend for browser-optimised data structures. * * @author danilatos@google.com (Daniel Danilatos) */ public final class JsoView extends JavaScriptObject { // As required by GWT protected JsoView() {} /** Construct an empty Jso */ public static native JsoView create() /*-{ return {}; }-*/; /** * Unsafely cast any jso to a JsoView, exposing its internals. * * @param jso * @return a JsoView of the input javascript object */ public static JsoView as(JavaScriptObject jso) { return jso.cast(); } /** * @param key * @return true if a value indexed by the given key is in the map */ public native boolean containsKey(String key) /*-{ return this[key] !== undefined; }-*/; /** * @param key * @return true if the given key exists in the map and is null */ public native boolean isNull(String key) /*-{ return this[key] === null; }-*/; /** * @param key * @return The value with the given key, or null if not present. The value is * assumed to be a boolean. The method may fail at runtime if the type * is not correct. */ public native boolean getBoolean(String key) /*-{ return this[key]; }-*/; /** * @param key * @return The value with the given key, or null if not present. The value is * assumed to be a string. The method may fail at runtime if the type * is not correct. */ public native String getString(String key) /*-{ return this[key]; }-*/; /** * @param key * @return The value with the given key, or null if not present. The value is * assumed to be a string. The method may fail at runtime if the type * is not correct. */ public native String getString(int key) /*-{ return this[key]; }-*/; /** * @param key * @return The value with the given key, or null if not present. The value is * assumed to be a primitive number. The method may fail at runtime if * the type is not correct. */ public native double getNumber(String key) /*-{ return this[key]; }-*/; /** * @param key * @return The value with the given key, or null if not present. The value is * assumed to be a JSO. The method may fail at runtime if the type * is not correct. */ public native JavaScriptObject getJso(String key) /*-{ return this[key]; }-*/; /** * @param key * @return The value with the given key, or null if not present. The value is * assumed to be a JSO. The method may fail at runtime if the type * is not correct. */ public native JavaScriptObject getJso(int key) /*-{ return this[key]; }-*/; /** * @param key * @return The value with the given key, or null if not present. The value is * assumed to be a JSO. The method may fail at runtime if the type * is not correct. */ public JsoView getJsoView(String key) { JavaScriptObject jso = getJso(key); return jso == null ? null : JsoView.as(jso); } /** * @param key * @return The value with the given key, or null if not present. The value is * assumed to be a JSO. The method may fail at runtime if the type * is not correct. */ public JsoView getJsoView(int key) { JavaScriptObject jso = getJso(key); return jso == null ? null : JsoView.as(jso); } /** * @param key * @return The value with the given key, or null if not present. The value is * assumed to be a "java" object. The method may fail at runtime if * the type is not correct. */ public native Object getObject(String key) /*-{ return this[key]; }-*/; /** * Same as {@link #getObject(String)} but does not require casting of the * return value */ public native <V> V getObjectUnsafe(String key) /*-{ return this[key]; }-*/; /** * Removes the given key from the map * @param key */ public native void remove(String key) /*-{ delete this[key]; }-*/; /** * Sets the value for the given key to null (does not remove it from the map) * @param key */ public native void setNull(String key) /*-{ this[key] = null; }-*/; /** * Sets the value for the key * @param key * @param value */ public native void setBoolean(String key, boolean value) /*-{ this[key] = value; }-*/; /** * Sets the value for the key * @param key * @param value */ public native void setString(String key, String value) /*-{ this[key] = value; }-*/; /** * Sets the value for the key * @param key * @param value */ public native void setNumber(String key, double value) /*-{ this[key] = value; }-*/; /** * Sets the value for the key * @param key * @param value */ public native void setJso(String key, JavaScriptObject value) /*-{ this[key] = value; }-*/; /** * Sets the value for the key * @param key * @param value */ public native void setObject(String key, Object value) /*-{ this[key] = value; }-*/; /** * Removes all entries from this jso. */ public final native void clear() /*-{ for (var key in this) { delete this[key]; } }-*/; /** * Tests whether this jso is empty. * * @return true if this map has no entries. */ public final native boolean isEmpty() /*-{ for (var k in this) { return false; } return true; }-*/; /** * Counts the number of entries in this jso. This is a linear time operation. */ public final native int countEntries() /*-{ var n = 0; for (var k in this) { n++; } return n; }-*/; /** * @return the first key in the iteration order, or null if the object is empty */ public final native String firstKey() /*-{ for (var k in this) { return k; } return null; }-*/; /** * Ruby/prototype.js style iterating idiom, using a callback. Equivalent to a * for-each loop. * * @param <T> The value type. It is up to the caller to make sure only values * of type T have been put into the Jso in the first place * @param proc */ public final native <T> void each(ProcV<T> proc) /*-{ for (var k in this) { proc. @org.waveprotocol.wave.model.util.ReadableStringMap.ProcV::apply(Ljava/lang/String;Ljava/lang/Object;) (k, this[k]); } }-*/; /** * Add all key value pairs from the source to the current map * * @param source */ public final native void putAll(JsoView source) /*-{ for (var k in source) { this[k] = source[k]; } }-*/; }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/client/common/util/IntMapJsoView.java
api/src/main/java/org/waveprotocol/wave/client/common/util/IntMapJsoView.java
/** * 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 org.waveprotocol.wave.client.common.util; import org.waveprotocol.wave.model.util.ReadableIntMap.ProcV; import com.google.gwt.core.client.JavaScriptObject; import java.util.HashMap; import java.util.Map; /** * A super fast and memory efficient map (directly uses a js object as the map, * and requires only 1 object). Only allows int keys, thus taking advantage of * the "perfect hashing" of ints with respect to javascript. * * No one other than JsoIntMap should use this class. * TODO(danilatos): Move the clever logic into JsoIntMap and delete this file. * * NOTE(danilatos): Does not use hasOwnProperty semantics. So it's possible for * spurious entries to appear in the map if we're not careful. Easily fixable, * but would incur a slight performance hit (I'm now just handwaving). * * TODO(dan): Use a different version from the GWT team once it is available * * @author danilatos@google.com (Daniel Danilatos) * @param <T> Type of values in the map. Keys are always ints. */ final class IntMapJsoView<T> extends JsoMapBase { /** * A function that accepts an accumulated value, a key and the corresponding * item from the map and returns the new accumulated value. * * @see IntMapJsoView#reduce(Object, Reduce) * @param <E> * int map's type parameter * @param <R> * The type of the value being accumulated */ public interface Reduce<E, R> { /** The function */ public R apply(R soFar, int key, E item); } /** Construct an empty IntMap */ public static native <T> IntMapJsoView<T> create() /*-{ return {}; }-*/; /** * Represent a java script native function that change the integer key into index key. * This is done because in chrome, it is 20 times faster to store string index than to store * numeric index if the number is > 2^15. * * The following time are recorded under chrome linux 4.0.266.0 * The recorderd time are in ms. * * iterations Numeric Index String index Hybrid time * 1024 1 2 0 * 2048 0 5 1 * 4096 1 14 1 * 8192 4 30 4 * 16384 8 63 9 * 32768 20 132 24 * 65536 266 264 148 * 131072 5551 513 404 * 262144 16719 1036 976 * * for numeric index < 2^15, it is 6 times faster to use numeric index * for string index > 2^15, it is 20 times faster to use string index * hybrid approach represents what we are doing here, i.e. use numeric index for value < 2^15 and * string index for value > 2^15 * * DESPITE THIS RESULT, it is very bad to use numeric index at all. Using the numeric index * slows down the javascript engine. We always uses String index in chrome. So DO NOT change * the code to do the hybrid approach. * * This function must be represented by JavaScriptObject and not normal java interfaces because * it's return data of different type depends on the input value. */ @SuppressWarnings("unused") // used in native method private static JavaScriptObject prefixer; @SuppressWarnings("unused") // used in native method private static JavaScriptObject evaler; static { setupPrefix(UserAgent.isChrome()); } private static native void setupPrefix(boolean usePrefix) /*-{ if (usePrefix) { @org.waveprotocol.wave.client.common.util.IntMapJsoView::prefixer = function(a) { return "a" + a; }; @org.waveprotocol.wave.client.common.util.IntMapJsoView::evaler = function(a) { return a[0] == "a" ? parseInt(a.substr(1, a.length)) : parseInt(a); } } else { @org.waveprotocol.wave.client.common.util.IntMapJsoView::prefixer = function(a) { return a; }; @org.waveprotocol.wave.client.common.util.IntMapJsoView::evaler = function(a) { return parseInt(a); } } }-*/; /** Construct a IntMap from a java Map */ public static <T> IntMapJsoView<T> fromMap(Map<Integer, T> map) { IntMapJsoView<T> intMap = create(); for (int key : map.keySet()) { intMap.put(key, map.get(key)); } return intMap; } protected IntMapJsoView() { } /** * @param key * @return true if a value indexed by the given key is in the map */ public native boolean has(int key) /*-{ var prefixer = @org.waveprotocol.wave.client.common.util.IntMapJsoView::prefixer; return this[prefixer(key)] !== undefined; }-*/; /** * @param key * @return The value with the given key, or null if not present */ public native T get(int key) /*-{ var prefixer = @org.waveprotocol.wave.client.common.util.IntMapJsoView::prefixer; return this[prefixer(key)]; }-*/; /** * Put the value in the map at the given key. Note: Does not return the old * value. * * @param key * @param value */ public native void put(int key, T value) /*-{ var prefixer = @org.waveprotocol.wave.client.common.util.IntMapJsoView::prefixer; this[prefixer(key)] = value; }-*/; /** * Remove the value with the given key from the map. Note: does not return the * old value. * * @param key */ public native void remove(int key) /*-{ var prefixer = @org.waveprotocol.wave.client.common.util.IntMapJsoView::prefixer; delete this[prefixer(key)]; }-*/; /** * Same as {@link #remove(int)}, but returns what was previously there, if * anything. * * @param key * @return what was previously there or null */ public final T removeAndReturn(int key) { T val = get(key); remove(key); return val; } /** * Ruby/prototype.js style iterating idiom, using a callbak. Equivalent to a * for-each loop. TODO(danilatos): Implement break and through a la * prototype.js if needed. * * @param proc */ public final native void each(ProcV<? super T> proc) /*-{ var evaler = @org.waveprotocol.wave.client.common.util.IntMapJsoView::evaler; for (var k in this) { proc. @org.waveprotocol.wave.model.util.ReadableIntMap.ProcV::apply(ILjava/lang/Object;) (evaler(k), this[k]); } }-*/; public final native T someValue() /*-{ for (var k in this) { return this[k] } return null; }-*/; /** * Same as ruby/prototype reduce. Same as functional foldl. Apply a function * to an accumulator and key/value in the map. The function returns the new * accumulated value. TODO(danilatos): Implement break and through a la * prototype.js if needed. * * @param initial * @param proc * @return The accumulated value * @param <R> * The accumulating type */ public final native <R> R reduce(R initial, Reduce<T, R> proc) /*-{ var reduction = initial; var evaler = @org.waveprotocol.wave.client.common.util.IntMapJsoView::evaler; for (var k in this) { reduction = proc. @org.waveprotocol.wave.client.common.util.IntMapJsoView.Reduce::apply(Ljava/lang/Object;ILjava/lang/Object;) (reduction, evaler(k), this[k]); } return reduction; }-*/; /** * Convert to a java Map */ public final Map<Integer, T> toMap() { return addToMap(new HashMap<Integer, T>()); } /** * Add all values to a java map. * * @param map * The map to add values to * @return The same map, for convenience. */ public final Map<Integer, T> addToMap(final Map<Integer, T> map) { each(new ProcV<T>() { public void apply(int key, T item) { map.put(key, item); } }); return map; } /** * Add all values to a IntMap. * * @param map * The map to add values to * @return The same map, for convenience. */ public final IntMapJsoView<T> addToMap(final IntMapJsoView<T> map) { each(new ProcV<T>() { public void apply(int key, T item) { map.put(key, item); } }); return map; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/client/common/util/QuirksConstants.java
api/src/main/java/org/waveprotocol/wave/client/common/util/QuirksConstants.java
/** * 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 org.waveprotocol.wave.client.common.util; import com.google.gwt.core.client.GWT; /** * Collection of constants defining various browser quirky behaviours. * * Each constant should be accompanied by a detailed comment, and a "Tested:" * section detailing which browsers and operating systems the quirk has been * tested on, so that it's easy to know what's untested as new browser versions * come out, etc. * * Sometimes an "Untested exceptions:" field is appropriate, to note exceptions * to the "Tested:" field, in particular if they are concerning and represent a * reasonable doubt as to the correctness of the field's value. * * It is preferable to use the constants in this class than to have logic that * switches on explicit browser checks. * * @author danilatos@google.com (Daniel Danilatos) */ public final class QuirksConstants { /** * Whether we get DOM Mutation events * * Tested: * Safari 3-4, Firefox 3-3.5, Chrome 1-2, IE7, IE8 * * Will IE9 give us mutation events? probably not. */ public static final boolean PROVIDES_MUTATION_EVENTS = UserAgent.isFirefox() || UserAgent.isWebkit(); /** * Whether the browser left normalises the caret in most cases (There are * exceptions, usually to do with links). * * Tested: * Safari 3*, Safari 4 beta, Firefox 3.0, IE7, IE8 */ public static final boolean USUALLY_LEFT_NORMALISES = UserAgent.isWebkit() || UserAgent.isWebkit(); /** * Certain versions of webkit have a specific hack implemented in them, where * they go against the regular left-normalised behaviour at the end of an * anchor boundary, if it has an href. They still report the cursor as being * left-normalised, but if the user types, text goes to the right, outside the * link. * * Tested: * All OS: Safari 3.2.1, Safari 4 beta, Chrome 1.0, Chrome 2.0 special sauce */ public static final boolean LIES_ABOUT_CARET_AT_LINK_END_BOUNDARY = UserAgent.isWebkit() && UserAgent.isAtLeastVersion(528, 0); /** * Similar to {@link #LIES_ABOUT_CARET_AT_LINK_END_BOUNDARY}, but does not * actually lie, just doesn't like reporting carets as being inside link * boundaries, and typing occurs outside as well. * * Tested: IE8 beta * * TODO(danilatos): check IE7 */ public static final boolean DOES_NOT_LEFT_NORMALISE_AT_LINK_END_BOUNDARY = UserAgent.isIE(); /** * If the user is typing, we always get a key event before the browser changes * the dom. * * Tested: * All OS: Safari 3.2.1, 4 beta, Chrome 1, 2, Firefox 3, IE7, IE8 * * Untested exceptions: Any IME on Linux! */ public static final boolean ALWAYS_GIVES_KEY_EVENT_BEFORE_CHANGING_DOM = UserAgent.isFirefox() || UserAgent.isIE7(); /** * Whether we get the magic 229 keycode for IME key events, at least for the * first one (sometimes we don't get key events for subsequent mutations). * * Tested: * All OS: Safari 3.2.1, 4 beta, Chrome 1, 2, Firefox 3.0 * * Untested exceptions: Any IME on Linux! */ public static final boolean CAN_TELL_WHEN_FIRST_KEY_EVENT_IS_IME = UserAgent.isIE() || UserAgent.isWebkit() || UserAgent.isWin(); /** * Whether the old school Ctrl+Insert, Shift+Delete, Shift+Insert shortcuts * for Copy, Cut, Paste work. * * Tested: All OS: Firefox 3, IE 7/8, Safari 3, Chrome 2 * * Untested exceptions: Safari on Windows */ public static final boolean HAS_OLD_SCHOOL_CLIPBOARD_SHORTCUTS = UserAgent.isWin() || UserAgent.isLinux(); // NOTE(danilatos): These selection constants, unless mentioned otherwise, // refer to selection boundaries (e.g. the start, or end, of a ranged // selection, or a collapsed selection). /** * Whether the selection is either cleared or correctly transformed by the * browser in at least the following scenarios: * - textNode.insertData adds to the cursor location, if it is after the * deletion point * - textNode.deleteData subtracts from the cursor location, if it is after * the deletion point * * Tested: Safari 3.2.1, FF 3.0, 3.5, Chrome 1, IE7, IE8 */ public static final boolean OK_SELECTION_ACROSS_TEXT_NODE_DATA_CHANGES = UserAgent.isFirefox() || UserAgent.isIE(); /** * Whether the selection is either cleared or correctly transformed by the * browser when text nodes are deleted. * * Gecko/IE preserve, Webkit clears selection. Both OK behaviours. * * Tested: Safari 3.2.1, FF 3.0, 3.5, Chrome 1, IE7, IE8 */ public static final boolean OK_SELECTION_ACROSS_NODE_REMOVALS = true; /** * Whether the browser moves the selection into the neighbouring text node * after a text node split before the selection point, or at least clears the * selection. * * Tested: Safari 3.2.1, FF 3.0, 3.5, Chrome 1, IE7, IE8 */ public static final boolean OK_SELECTION_ACROSS_TEXT_NODE_SPLITS = UserAgent.isIE(); /** * In this case, only clearing occurs by Webkit. Other two browsers move the * selection to the point where the moved node was. Which is BAD for wrapping! * * Tested: Safari 3.2.1, FF 3.0, 3.5, Chrome 1, IE7, IE8 * * @see #PRESERVES_SEMANTIC_SELECTION_ACROSS_MUTATIONS_OR_CLEARS_IT */ public static final boolean OK_SELECTION_ACROSS_MOVES = UserAgent.isWebkit(); /** * Preserves changes to text nodes made by calling methods on the text nodes * directly (i.e. not moving or deleting the text nodes). */ public static final boolean PRESERVES_SEMANTIC_SELECTION_ACROSS_INTRINSIC_TEXT_NODE_CHANGES = OK_SELECTION_ACROSS_TEXT_NODE_DATA_CHANGES && OK_SELECTION_ACROSS_TEXT_NODE_SPLITS; /** * Whether the selection preservation is completely reliable across mutations * in terms of correctness. It might get cleared in some circumstances, but * that's OK, we can just check if the selection is gone and restore it. We * don't need to transform it for correctness. * * The biggest problem here is wrap. Currently implemented with insertBefore, * it breaks selections in all browsers, even IE, AND IE doesn't clear the * selection, just moves it. Damn! Anyway, there might be a smarter way to * implement wrap - perhaps using an exec command to apply a styling to a * region and using the resulting wrapper nodes... but that's a long way off. * * Tested: Safari 3.2.1, FF 3.0, 3.5, Chrome 1, IE7, IE8 */ public static final boolean PRESERVES_SEMANTIC_SELECTION_ACROSS_MUTATIONS_OR_CLEARS_IT = OK_SELECTION_ACROSS_TEXT_NODE_DATA_CHANGES && OK_SELECTION_ACROSS_TEXT_NODE_SPLITS && OK_SELECTION_ACROSS_MOVES; /** * Whether changing stuff in the middle of a ranged selection (that doesn't * affect the selection end points in any way), such as splitting some * entirely contained text node, affects the ranged selection. With firefox, * it appears that the selection is still "correct", but visually new text * nodes inserted don't get highlighted as selected, which is bad. * * Tested: Safari 3.2.1, FF 3.0, IE8 */ public static final boolean RANGED_SELECTION_AFFECTED_BY_INTERNAL_CHANGED = UserAgent.isFirefox(); /** * True if IME input in not totally munged by adjacent text node mutations * * Tested: * Safari 3.2.1, FF 3.0, 3.5, Chrome 1, IE7, IE8 */ public static final boolean PRESERVES_IME_STATE_ACROSS_ADJACENT_CHANGES = UserAgent.isIE(); /** * True if we can do the __proto__ override trick to remove defaults method * in a JSO. * WARNING(dnailatos/reuben) Should be kept as static constant for * speed reasons in string map implementation. * * Tested: Safari 4, FF 3.0, 3.5, Chrome 3-4, IE8 */ public static final boolean DOES_NOT_SUPPORT_JSO_PROTO_FIELD = UserAgent.isIE(); /** * It appears that in some browsers, if you stopPropagation() an IME * composition or contextmenu event, the default action for the event is not * executed (as if you had cancelled it) * * TODO(danilatos): File a bug * * Tested: * FF 3.0 * * Untested: * Everything else (at time of writing, nothing else has composition * events...) */ public static final boolean CANCEL_BUBBLING_CANCELS_IME_COMPOSITION_AND_CONTEXTMENU = UserAgent.isFirefox(); /** * True if mouse events have rangeParent and rangeOffset fields. * * Tested: * FF 3.0, 3.6 * Safari 4 * Chrome 5 */ public static final boolean SUPPORTS_EVENT_GET_RANGE_METHODS = UserAgent.isFirefox(); /** * True if preventDefault stops a native context menu from being shown. In * firefox this is not the case when dom.event.contextmenu.enabled is set. * * Tested: * FF 3.0, 3.6 */ public static final boolean PREVENT_DEFAULT_STOPS_CONTEXTMENT = !UserAgent.isFirefox(); /** * True if displaying a context menu updates the current selection. Safari selects * the word clicked unless you click on the current selection, Firefox does not * change the selection and Chrome and IE clears the selection unless you click * on the current selection. * * The selection that is active on mousedown will, in all browsers, be the * original selection and the selection on the contextmenu event will be the new * one. * * Tested: * FF 3.0, 3.5 * Chrome 5 * Safari 4 * IE 8 */ public static final boolean CONTEXTMENU_SETS_SELECTION = !UserAgent.isFirefox(); /** * True if the browser has the setBaseAndExtent JS method to allow better setting of * the selection within the browser. * * So far, only webkit browsers have this in their API, and documentation is scarce. See: * http://developer.apple.com/DOCUMENTATION/AppleApplications/Reference/WebKitDOMRef * /DOMSelection_idl/Classes/DOMSelection/index.html#//apple_ref/idl/instm * /DOMSelection/setBaseAndExtent/void/(inNode,inlong,inNode,inlong) */ public static final boolean HAS_BASE_AND_EXTENT = UserAgent.isWebkit(); /** * Chrome on Mac generates doesn't keypress for command combos, only keydown. * * In general, it makes sense to only fire the keypress event if the combo * generates content. https://bugs.webkit.org/show_bug.cgi?id=30397 * * However since it is the odd one out here, it is listed as a * quirk. */ public static final boolean COMMAND_COMBO_DOESNT_GIVE_KEYPRESS = UserAgent.isMac() && UserAgent.isChrome(); /** * True if the browser has native support for getElementsByClassName. * * Tested: * Chrome, Safari 3.1, Firefox 3.0 */ public static final boolean SUPPORTS_GET_ELEMENTS_BY_CLASSNAME = GWT.isScript() && checkGetElementsByClassNameSupport(); /** * True if the browser supports composition events. * * (This does not differentiate between the per-browser composition event quirks, * such as whether they provide a text vs a compositionupdate event, or other * glitches). * * Tested: * Chrome 3.0, 4.0; Safari 4; FF 3.0, 3.5; IE 7,8 */ public static final boolean SUPPORTS_COMPOSITION_EVENTS = UserAgent.isFirefox() || (UserAgent.isWebkit() && UserAgent.isAtLeastVersion(532, 5)); /** * True if the browser does an extra modification of the DOM after the * compositionend event, and also fires a text input event if the composition * was not cancelled. * * Tested: Chrome 4.0; FF 3.0, 3.5; */ public static final boolean MODIFIES_DOM_AND_FIRES_TEXTINPUT_AFTER_COMPOSITION = UserAgent.isWebkit(); // Put an upper bound on the version here when it's fixed... /** * True if the browser keeps the selection in an empty span after the * app has programmatically set it there. * * Tested: * Chrome 3.0, 4.0; Safari 3, 4; FF 3.0, 3.5; IE 7,8 */ public static final boolean SUPPORTS_CARET_IN_EMPTY_SPAN = UserAgent.isFirefox(); /** * True if the browser automatically scrolls a contentEditable element * into view when we set focus on the element * * Tested: * Chrome 5.0.307.11 beta / linux, Safari 4.0.4 / mac, Firefox 3.0.7 + 3.6 / linux */ public static final boolean ADJUSTS_SCROLL_TOP_WHEN_FOCUSING = UserAgent.isWebkit(); /** * True if the browser does not emit a paste event for plaintext paste. * This was a bug on Webkit and has been fixed and pushed to Chrome 4+ * * Tested: * Chrome 4.0.302.3; Safari 4.05 Mac */ public static final boolean PLAINTEXT_PASTE_DOES_NOT_EMIT_PASTE_EVENT = UserAgent.isSafari(); /** * True if the browser supports input type 'search'. * * Tested: * Chrome 9.0, Chrome 4.0 */ public static final boolean SUPPORTS_SEARCH_INPUT = UserAgent.isWebkit(); /** * True if the browser sanitizes pasted content to contenteditable to * prevent script execution. * * Tested: * Chrome 9.0, Safari 5, FF 3.5, FF 4.0 */ public static final boolean SANITIZES_PASTED_CONTENT = (UserAgent.isWebkit() && UserAgent.isAtLeastVersion(533, 16)) || (UserAgent.isFirefox() && UserAgent.isAtLeastVersion(4, 0)); private static native boolean checkGetElementsByClassNameSupport() /*-{ return !!document.body.getElementsByClassName; }-*/; private QuirksConstants(){} }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/client/common/util/UserAgent.java
api/src/main/java/org/waveprotocol/wave/client/common/util/UserAgent.java
/** * 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 org.waveprotocol.wave.client.common.util; /** * Information about the current user agent. Some of the information is * dynamically determined at runtime, other information is determined at compile * time as it is baked into the particular permutation with the deferred binding * mechanism. * * Methods that are statically evaluable allow conditional compilation for * different user agents. * * e.g. currently, the following code: * * if (UserAgent.isIE()) { * // do IE-specific implementation * } else { * // do non-IE implementation * } * * should for "user.agent" set to "ie6" compile down to just the IE-specific * implementation. * * It is not exposed as part of this API which methods are statically determined * and which are not, as this may be subject to change. In general it should not * matter as the cost of a runtime check is very cheap. If it does matter, it is * up to the caller to know and keep track of the current state of affairs. * */ public abstract class UserAgent { /** * @return true iff the user agent uses webkit */ public static boolean isWebkit() { return UserAgentStaticProperties.get().isWebkit(); } /** * @return true iff the user agent uses mobile webkit */ public static boolean isMobileWebkit() { return UserAgentStaticProperties.get().isMobileWebkit(); } /** * @return true iff the user.agent GWT property is "safari" */ public static boolean isSafari() { return UserAgentStaticProperties.get().isSafari(); } /** * @return true iff the user.agent GWT property is "gecko" or "gecko1_8" */ public static boolean isFirefox() { return UserAgentStaticProperties.get().isFirefox(); } /** * @return true iff the user.agent GWT property is "ie6" */ public static boolean isIE() { return UserAgentStaticProperties.get().isIE(); } /** * @return true iff the user.agent GWT property is "android" */ public static boolean isAndroid() { return UserAgentStaticProperties.get().isAndroid(); } /** * @return true iff the user.agent GWT property is "iphone" */ public static boolean isIPhone() { return UserAgentStaticProperties.get().isIPhone(); } /** * @return true if this is the chrome browser */ public static boolean isChrome() { return UserAgentRuntimeProperties.get().isChrome(); } public static boolean isIE7() { return UserAgentRuntimeProperties.get().isIe7(); } public static boolean isIE8() { return UserAgentRuntimeProperties.get().isIe8(); } /** * @return true if we are on OSX */ public static boolean isMac() { return UserAgentRuntimeProperties.get().isMac(); } /** * @return true if we are on Windows */ public static boolean isWin() { return UserAgentRuntimeProperties.get().isWin(); } /** * @return true if we are on Linux */ public static boolean isLinux() { return UserAgentRuntimeProperties.get().isLinux(); } /** * Debug method that returns the user-agent string. * * NOTE(user): FOR DEBUGGING PURPOSES ONLY. DO NOT USE FOR PROGRAM LOGIC. */ public static String debugUserAgentString() { return UserAgentRuntimeProperties.get().getUserAgent(); } /** * @return whether the current user agent version is at least the one given by * the method parameters. */ public static boolean isAtLeastVersion(int major, int minor) { return UserAgentRuntimeProperties.get().isAtLeastVersion(major, minor); } /** * Do not use this for program logic - for debugging only. For program logic, * instead use {@link #isAtLeastVersion(int, int)} */ public static int debugGetMajorVer() { return UserAgentRuntimeProperties.get().getMajorVer(); } /** * Do not use this for program logic - for debugging only. For program logic, * instead use {@link #isAtLeastVersion(int, int)} */ public static int debugGetMinorVer() { return UserAgentRuntimeProperties.get().getMinorVer(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/client/common/util/SignalKeyLogic.java
api/src/main/java/org/waveprotocol/wave/client/common/util/SignalKeyLogic.java
/** * 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 org.waveprotocol.wave.client.common.util; import com.google.common.annotations.VisibleForTesting; import org.waveprotocol.wave.client.common.util.SignalEvent.KeySignalType; import org.waveprotocol.wave.model.util.CollectionUtils; import org.waveprotocol.wave.model.util.ReadableStringMap.ProcV; import org.waveprotocol.wave.model.util.StringMap; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.user.client.Event; import java.util.HashSet; import java.util.Set; /** * Instances of this class encapsulate the event to signal mapping logic for a * specific environment (os/browser). * * Contains as much of the signal event logic as possible in a POJO testable * manner. * * @author danilatos@google.com (Daniel Danilatos) */ public final class SignalKeyLogic { /** * For webkit + IE * I think also all browsers on windows? */ public static final int IME_CODE = 229; private static final String DELETE_KEY_IDENTIFIER = "U+007F"; //TODO(danilatos): Use int map private static final Set<Integer> NAVIGATION_KEYS = new HashSet<Integer>(); private static final StringMap<Integer> NAVIGATION_KEY_IDENTIFIERS = CollectionUtils.createStringMap(); static { NAVIGATION_KEY_IDENTIFIERS.put("Left", KeyCodes.KEY_LEFT); NAVIGATION_KEY_IDENTIFIERS.put("Right", KeyCodes.KEY_RIGHT); NAVIGATION_KEY_IDENTIFIERS.put("Up", KeyCodes.KEY_UP); NAVIGATION_KEY_IDENTIFIERS.put("Down", KeyCodes.KEY_DOWN); NAVIGATION_KEY_IDENTIFIERS.put("PageUp", KeyCodes.KEY_PAGEUP); NAVIGATION_KEY_IDENTIFIERS.put("PageDown", KeyCodes.KEY_PAGEDOWN); NAVIGATION_KEY_IDENTIFIERS.put("Home", KeyCodes.KEY_HOME); NAVIGATION_KEY_IDENTIFIERS.put("End", KeyCodes.KEY_END); NAVIGATION_KEY_IDENTIFIERS.each(new ProcV<Integer>() { public void apply(String key, Integer keyCode) { NAVIGATION_KEYS.add(keyCode); } }); } public enum UserAgentType { WEBKIT, GECKO, IE } public enum OperatingSystem { WINDOWS, MAC, LINUX } @VisibleForTesting public static class Result { @VisibleForTesting public int keyCode; // Sentinal by default for testing purposes @VisibleForTesting public KeySignalType type = KeySignalType.SENTINAL; } private final UserAgentType userAgent; private final boolean commandIsCtrl; // Hack, get rid of this final boolean commandComboDoesntGiveKeypress; /** * @param userAgent * @param os Operating system */ public SignalKeyLogic(UserAgentType userAgent, OperatingSystem os, boolean commandComboDoesntGiveKeypress) { this.userAgent = userAgent; this.commandComboDoesntGiveKeypress = commandComboDoesntGiveKeypress; commandIsCtrl = os != OperatingSystem.MAC; } public boolean commandIsCtrl() { return commandIsCtrl; } public void computeKeySignalType( Result result, String typeName, int keyCode, int which, String keyIdentifier, boolean metaKey, boolean ctrlKey, boolean altKey, boolean shiftKey) { boolean ret = true; int typeInt; if ("keydown".equals(typeName)) { typeInt = Event.ONKEYDOWN; } else if ("keypress".equals(typeName)) { typeInt = Event.ONKEYPRESS; } else if ("keyup".equals(typeName)) { result.type = null; return; } else { throw new AssertionError("Non-key-event passed to computeKeySignalType"); } KeySignalType type; int computedKeyCode = which != 0 ? which : keyCode; if (computedKeyCode == 10) { computedKeyCode = KeyCodes.KEY_ENTER; } // For non-firefox browsers, we only get keydown events for IME, no keypress boolean isIME = computedKeyCode == IME_CODE; boolean commandKey = commandIsCtrl ? ctrlKey : metaKey; switch (userAgent) { case WEBKIT: // This is a bit tricky because there are significant differences // between safari 3.0 and safari 3.1... // We could probably actually almost use the same code that we use for IE // for safari 3.1, because with 3.1 the webkit folks made a big shift to // get the events to be in line with IE for compatibility. 3.0 events // are a lot more similar to FF, but different enough to need special // handling. However, it seems that using more advanced features like // keyIdentifier for safaris is probably better and more future-proof, // as well as being compatible between the two, so for now we're not // using IE logic for safari 3.1 // Weird special large keycode numbers for safari 3.0, where it gives // us keypress events (though they happen after the dom is changed, // for some things like delete. So not too useful). The number // 63200 is known as the cutoff mark. if (typeInt == Event.ONKEYDOWN && computedKeyCode > 63200) { result.type = null; return; } else if (typeInt == Event.ONKEYPRESS) { // Skip keypress for tab and escape, because they are the only non-input keys // that don't have keycodes above 63200. This is to prevent them from being treated // as INPUT in the || = keypress below. See (X) below if (computedKeyCode == KeyCodes.KEY_ESCAPE || computedKeyCode == KeyCodes.KEY_TAB) { result.type = null; return; } } // boolean isPossiblyCtrlInput = typeInt == Event.ONKEYDOWN && ret.getCtrlKey(); boolean isActuallyCtrlInput = false; boolean startsWithUPlus = keyIdentifier != null && keyIdentifier.startsWith("U+"); // Need to use identifier for the delete key because the keycode conflicts // with the keycode for the full stop. if (isIME) { // If is IME, override the logic below - we get keyIdentifiers for IME events, // but those are basically useless as the event is basically still an IME input // event (e.g. keyIdentifier might say "Up", but it's certainly not navigation, // it's just the user selecting from the IME dialog). type = KeySignalType.INPUT; } else if (DELETE_KEY_IDENTIFIER.equals(keyIdentifier) || computedKeyCode == KeyCodes.KEY_BACKSPACE) { type = KeySignalType.DELETE; } else if (NAVIGATION_KEY_IDENTIFIERS.containsKey(keyIdentifier)) { type = KeySignalType.NAVIGATION; // Escape, backspace and context-menu-key (U+0010) are, to my knowledge, // the only non-navigation keys that // have a "U+..." keyIdentifier, so we handle them explicitly. // (Backspace was handled earlier). } else if (computedKeyCode == KeyCodes.KEY_ESCAPE || "U+0010".equals(keyIdentifier)) { type = KeySignalType.NOEFFECT; } else if ( computedKeyCode < 63200 && // if it's not a safari 3.0 non-input key (See (X) above) (typeInt == Event.ONKEYPRESS || // if it's a regular keypress startsWithUPlus || computedKeyCode == KeyCodes.KEY_ENTER)) { type = KeySignalType.INPUT; isActuallyCtrlInput = ctrlKey || (commandComboDoesntGiveKeypress && commandKey); } else { type = KeySignalType.NOEFFECT; } // Maybe nullify it with the same logic as IE, EXCEPT for the special // Ctrl Input webkit behaviour, and IME for windows if (isActuallyCtrlInput) { if (computedKeyCode == KeyCodes.KEY_ENTER) { ret = typeInt == Event.ONKEYDOWN; } // HACK(danilatos): Don't actually nullify isActuallyCtrlInput for key press. // We get that for AltGr combos on non-mac computers. } else if (isIME || keyCode == KeyCodes.KEY_TAB) { ret = typeInt == Event.ONKEYDOWN; } else { ret = maybeNullWebkitIE(ret, typeInt, type); } if (!ret) { result.type = null; return; } break; case GECKO: boolean hasKeyCodeButNotWhich = keyCode != 0 && which == 0; // Firefox is easy for deciding signal events, because it issues a keypress for // whenever we would want a signal. So we can basically ignore all keydown events. // It also, on all OSes, does any default action AFTER the keypress (even for // things like Ctrl/Meta+C, etc). So keypress is perfect for us. // Ctrl+Space is an exception, where we don't get a keypress // Firefox also gives us keypress events even for Windows IME input if (ctrlKey && !altKey && !shiftKey && computedKeyCode == ' ') { if (typeInt != Event.ONKEYDOWN) { result.type = null; return; } } else if (typeInt == Event.ONKEYDOWN) { result.type = null; return; } // Backspace fails the !hasKeyCodeButNotWhich test, so check it explicitly first if (computedKeyCode == KeyCodes.KEY_BACKSPACE) { type = KeySignalType.DELETE; // This 'keyCode' but not 'which' works very nicely for catching normal typing input keys, // the only 'exceptions' I've seen so far are bksp & enter which have both } else if (!hasKeyCodeButNotWhich || computedKeyCode == KeyCodes.KEY_ENTER || computedKeyCode == KeyCodes.KEY_TAB) { type = KeySignalType.INPUT; } else if (computedKeyCode == KeyCodes.KEY_DELETE) { type = KeySignalType.DELETE; } else if (NAVIGATION_KEYS.contains(computedKeyCode)) { type = KeySignalType.NAVIGATION; } else { type = KeySignalType.NOEFFECT; } break; case IE: // Unfortunately IE gives us the least information, so there are no nifty tricks. // So we pretty much need to use some educated guessing based on key codes. // Experimentation page to the rescue. boolean isKeydownForInputKey = isInputKeyCodeIE(computedKeyCode); // IE has some strange behaviour with modifiers and whether or not there will // be a keypress. Ctrl kills the keypress, unless shift is also held. // Meta doesn't kill it. Alt always kills the keypress, overriding other rules. boolean hasModifiersThatResultInNoKeyPress = altKey || (ctrlKey && !shiftKey); if (typeInt == Event.ONKEYDOWN) { if (isKeydownForInputKey) { type = KeySignalType.INPUT; } else if (computedKeyCode == KeyCodes.KEY_BACKSPACE || computedKeyCode == KeyCodes.KEY_DELETE) { type = KeySignalType.DELETE; } else if (NAVIGATION_KEYS.contains(computedKeyCode)) { type = KeySignalType.NAVIGATION; } else { type = KeySignalType.NOEFFECT; } } else { // Escape is the only non-input thing that has a keypress event if (computedKeyCode == KeyCodes.KEY_ESCAPE) { result.type = null; return; } assert typeInt == Event.ONKEYPRESS; // I think the guessCommandFromModifiers() check here isn't needed, // but i feel safer putting it in. type = KeySignalType.INPUT; } if (hasModifiersThatResultInNoKeyPress || isIME || computedKeyCode == KeyCodes.KEY_TAB) { ret = typeInt == Event.ONKEYDOWN ? ret : false; } else { ret = maybeNullWebkitIE(ret, typeInt, type); } if (!ret) { result.type = null; return; } break; default: throw new UnsupportedOperationException("Unhandled user agent"); } if (ret) { result.type = type; result.keyCode = computedKeyCode; } else { result.type = null; return; } } private static final boolean isInputKeyCodeIE(int keyCode) { /* DATA ---- For KEYDOWN: "Input" 48-57 (numbers) 65-90 (a-z) 96-111 (Numpad digits & other keys, with numlock off. with numlock on, they behave like their corresponding keys on the rest of the keyboard) 186-192 219-222 (random non-alphanumeric next to letters on RHS + backtick) 229 Code that the input has passed to an IME Non-"input" < 48 ('0') 91-93 (Left & Right Win keys, ContextMenu key) 112-123 (F1-F12) 144-5 (NUMLOCK,SCROLL LOCK) For KEYPRESS: only "input" things get this event! yay! not even backspace! Well, one exception: ESCAPE */ // boundaries in keycode ranges where the keycode for a keydown is for an input // key. at "ON" it is, starting from the number going up, and the opposite for "OFF". final int A_ON = 48; final int B_OFF = 91; final int C_ON = 96; final int D_OFF = 112; final int E_ON = 186; return (keyCode == 9 || keyCode == 32 || keyCode == 13) || // And tab, enter & spacebar, of course! (keyCode >= A_ON && keyCode < B_OFF) || (keyCode >= C_ON && keyCode < D_OFF) || (keyCode >= E_ON); } /** * Common logic between Webkit and IE for deciding whether we want the keydown * or the keypress */ private static boolean maybeNullWebkitIE(boolean ret, int typeInt, KeySignalType type) { // Use keydown as the signal for everything except input. // This is because the mutation always happens after the keypress for // input (this is especially important for chrome, // which interleaves deferred commands between keydown and keypress). // // For everything else, keypress is redundant with keydown, and also, the resulting default // dom mutation (if any) often happens after the keydown but before the keypress in webkit. // Also, if the 'Command' key is held for chrome/safari etc, we want to get the keydown // event, NOT the keypress event, for everything because of things like ctrl+c etc. // where sometimes it'll happen just after the keydown, or sometimes we just won't // get a keypress at all if (typeInt == (type == KeySignalType.INPUT ? Event.ONKEYDOWN : Event.ONKEYPRESS)) { return false; } return ret; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/client/common/util/SignalEventImpl.java
api/src/main/java/org/waveprotocol/wave/client/common/util/SignalEventImpl.java
/** * 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 org.waveprotocol.wave.client.common.util; import org.waveprotocol.wave.client.common.util.SignalKeyLogic.OperatingSystem; import org.waveprotocol.wave.client.common.util.SignalKeyLogic.UserAgentType; import org.waveprotocol.wave.model.util.CollectionUtils; import org.waveprotocol.wave.model.util.StringSet; import com.google.gwt.dom.client.Element; import com.google.gwt.user.client.Event; /** * Attempts to bring sanity to the incredibly complex and inconsistent world of * browser events, especially with regards to key events. * * A new concept of the "signal" is introduced. A signal is basically an event, * but an event that we actually care about, with the information we care about. * Redundant events are merged into a single signal. For key events, a signal * corresponds to the key-repeat signal we get from the keyboard. For normal * typing input, this will always be the keypress event. For other types of key * events, it depends on the browser. For clipboard events, the "beforeXYZ" and * "XYZ" events are merged into a single one, the one that actually happens * right before the action (browser dependent). Key events are also classified * into subtypes identified by KeySignalType. This reflects the intended usage * of the event, not something to do with the event data itself. * * Currently the "filtering" needs to be done manually - simply construct a * signal from an event using {@link #create(Event, boolean)}, and if it returns null, * drop the event and do nothing with it (cancelling bubbling might be a good * idea though). * * NOTE(danilatos): getting the physical key pressed, even on a key down, is * inherently not possible without a big lookup table, because of international * input methods. e.g. press 'b' but in greek mode on safari on osx. nothing in * any of the events you receive will tell you it was a 'b', instead, you'll get * a beta for the keypress and 0 (zero) for the keydown. mmm, useful! * * TODO(danilatos): Hook this into the application's event plumbing in a more * invasive manner. * * @author danilatos@google.com (Daniel Danilatos) */ public class SignalEventImpl implements SignalEvent { public interface SignalEventFactory<T extends SignalEventImpl> { T create(); } public static SignalEventFactory<SignalEventImpl> DEFAULT_FACTORY = new SignalEventFactory<SignalEventImpl>() { @Override public SignalEventImpl create() { return new SignalEventImpl(); } }; interface NativeEvent { String getType(); int getButton(); boolean getCtrlKey(); boolean getMetaKey(); boolean getAltKey(); boolean getShiftKey(); void preventDefault(); void stopPropagation(); } /** * @param event * @return True if the given event is a key event */ public static boolean isKeyEvent(Event event) { return KEY_EVENTS.contains(event.getType()); } private static final UserAgentType currentUserAgent = (UserAgent.isWebkit() ? UserAgentType.WEBKIT : ( UserAgent.isFirefox() ? UserAgentType.GECKO : UserAgentType.IE)); private static final OperatingSystem currentOs = (UserAgent.isWin() ? OperatingSystem.WINDOWS : ( UserAgent.isMac() ? OperatingSystem.MAC : OperatingSystem.LINUX)); private static final SignalKeyLogic logic = new SignalKeyLogic( currentUserAgent, currentOs, QuirksConstants.COMMAND_COMBO_DOESNT_GIVE_KEYPRESS); /** * This variable will be filled with mappings of unshifted keys to their shifted versions. */ private static final int[] shiftMappings = new int[128]; static { for (int a = 'A'; a <= 'Z'; a++) { shiftMappings[a] = a + 'a' - 'A'; } // TODO(danilatos): Who knows what these mappings should be on other // keyboard layouts... e.g. pound signs? euros? etc? argh! shiftMappings['1'] = '!'; shiftMappings['2'] = '@'; shiftMappings['3'] = '#'; shiftMappings['4'] = '$'; shiftMappings['5'] = '%'; shiftMappings['6'] = '^'; shiftMappings['7'] = '&'; shiftMappings['8'] = '*'; shiftMappings['9'] = '('; shiftMappings['0'] = ')'; shiftMappings['`'] = '~'; shiftMappings['-'] = '_'; shiftMappings['='] = '+'; shiftMappings['['] = '{'; shiftMappings[']'] = '}'; shiftMappings['\\'] = '|'; shiftMappings[';'] = ':'; shiftMappings['\''] = '"'; shiftMappings[','] = '<'; shiftMappings['.'] = '>'; shiftMappings['/'] = '?'; // invalidate the inverse mappings for (int i = 1; i < shiftMappings.length; i++) { int m = shiftMappings[i]; if (m > 0) { shiftMappings[m] = i; } } } private static final StringSet KEY_EVENTS = CollectionUtils.createStringSet(); private static final StringSet COMPOSITION_EVENTS = CollectionUtils.createStringSet(); private static final StringSet MOUSE_EVENTS = CollectionUtils.createStringSet(); private static final StringSet MOUSE_BUTTON_EVENTS = CollectionUtils.createStringSet(); private static final StringSet MOUSE_BUTTONLESS_EVENTS = CollectionUtils.createStringSet(); private static final StringSet FOCUS_EVENTS = CollectionUtils.createStringSet(); private static final StringSet CLIPBOARD_EVENTS = CollectionUtils.createStringSet(); /** * Events affected by * {@link QuirksConstants#CANCEL_BUBBLING_CANCELS_IME_COMPOSITION_AND_CONTEXTMENU}. */ private static final StringSet CANCEL_BUBBLE_QUIRKS = CollectionUtils.createStringSet(); static { for (String e : new String[]{"keydown", "keypress", "keyup"}) { KEY_EVENTS.add(e); } for (String e : new String[]{ "compositionstart", "compositionend", "compositionupdate", "text"}) { COMPOSITION_EVENTS.add(e); CANCEL_BUBBLE_QUIRKS.add(e); } COMPOSITION_EVENTS.add("textInput"); CANCEL_BUBBLE_QUIRKS.add("contextmenu"); for (String e : new String[]{ "mousewheel", "DOMMouseScroll", "mousemove", "mouseover", "mouseout", /* not strictly a mouse event*/ "contextmenu"}) { MOUSE_BUTTONLESS_EVENTS.add(e); MOUSE_EVENTS.add(e); } for (String e : new String[]{ "mousedown", "mouseup", "click", "dblclick"}) { MOUSE_BUTTON_EVENTS.add(e); MOUSE_EVENTS.add(e); } for (String e : new String[]{"focus", "blur", "beforeeditfocus"}) { FOCUS_EVENTS.add(e); } for (String e : new String[]{"cut", "copy", "paste"}) { CLIPBOARD_EVENTS.add(e); CLIPBOARD_EVENTS.add("before" + e); } } protected NativeEvent nativeEvent; private KeySignalType keySignalType = null; private int cachedKeyCode = -1; private boolean hasBeenConsumed = false; protected SignalEventImpl() { } static class JsoNativeEvent extends Event implements NativeEvent { protected JsoNativeEvent() {} } /** * Create a signal from an event, possibly filtering the event * if it is deemed redundant. * * If the event is to be filtered, null is returned, and bubbling * is cancelled if cancelBubbleIfNullified is true. * (but the default is not prevented). * * NOTE(danilatos): So far, for key events, the following have been tested: * - Safari 3.1 OS/X (incl. num pad, with USB keyboard) * - Safari 3.0 OS/X, hosted mode only (so no ctrl+c, etc) * - Firefox 3, OS/X, WinXP * - IE7, WinXP * Needs testing: * - FF3 linux, Safari 3.0/3.1 Windows * - All kinds of weirdo keyboards (mac, international) * - Linux IME * * Currently, only key events have serious logic applied to them. * Maybe some logic for copy/paste, and mouse events? * * @param event Raw Event JSO * @param cancelBubbleIfNullified stops propagation if the event is nullified * @return SignalEvent mapping, or null, if the event is to be discarded */ public static SignalEventImpl create(Event event, boolean cancelBubbleIfNullified) { return create(DEFAULT_FACTORY, event, cancelBubbleIfNullified); } public static <T extends SignalEventImpl> T create(SignalEventFactory<T> factory, Event event, boolean cancelBubbleIfNullified) { if (hasBeenConsumed(event)) { return null; } else { T signal = createInner(factory, event); if (cancelBubbleIfNullified && signal == null) { event.stopPropagation(); } return signal; } } private static boolean hasBeenConsumed(Event event) { SignalEventImpl existing = getFor(null, event); return existing != null && existing.hasBeenConsumed(); } private static final String EVENT_PROP = "$se"; @SuppressWarnings("unchecked") private static <T extends SignalEventImpl> T getFor(SignalEventFactory<T> factory, Event event) { return (T) (SignalEventImpl) event.<JsoView>cast().getObject(EVENT_PROP); } private static <T extends SignalEventImpl> T createFor( SignalEventFactory<T> factory, Event event) { T signal = factory.create(); event.<JsoView>cast().setObject(EVENT_PROP, signal); return signal; } /** This would be a static local variable if java allowed it. Grouping it here. */ private static final SignalKeyLogic.Result computeKeySignalTypeResult = new SignalKeyLogic.Result(); private static <T extends SignalEventImpl> T createInner( SignalEventFactory<T> factory, Event event) { SignalKeyLogic.Result keySignalResult; if (isKeyEvent(event)) { keySignalResult = computeKeySignalTypeResult; String keyIdentifier = getKeyIdentifier(event); logic.computeKeySignalType(keySignalResult, event.getType(), getNativeKeyCode(event), getWhich(event), keyIdentifier, event.getMetaKey(), event.getCtrlKey(), event.getAltKey(), event.getShiftKey()); } else { keySignalResult = null; } return createInner(createFor(factory, event), event.<JsoNativeEvent>cast(), keySignalResult); } /** * Populate a SignalEventImpl with the necessary information * * @param ret * @param keySignalResult only required if it's a key event * @return the signal, or null if it is to be ignored. */ protected static <T extends SignalEventImpl> T createInner(T ret, NativeEvent event, SignalKeyLogic.Result keySignalResult) { ret.nativeEvent = event; if (ret.isKeyEvent()) { KeySignalType type = keySignalResult.type; if (type != null) { ret.cacheKeyCode(keySignalResult.keyCode); ret.setup(type); } else { ret = null; } } else if ((UserAgent.isIE() ? "paste" : "beforepaste").equals(event.getType())) { // Only want 'beforepaste' for ie and 'paste' for everything else. // TODO(danilatos): Generalise clipboard events ret = null; } // TODO: return null if it's something we should ignore. return ret; } public static native int getNativeKeyCode(Event event) /*-{ return event.keyCode || 0; }-*/; public static native int getWhich(Event event) /*-{ return event.which || 0; }-*/; public static native String getKeyIdentifier(Event event) /*-{ return event.key || event.keyIdentifier }-*/; /** * @return Event type as a string, e.g. "keypress" */ public final String getType() { return nativeEvent.getType(); } /** * @return The target element of the event */ public Element getTarget() { return asEvent().getTarget(); } /** * @return true if the event is a key event * TODO(danilatos): Have a top level EventSignalType enum */ public final boolean isKeyEvent() { return KEY_EVENTS.contains(nativeEvent.getType()); } /** * @return true if it is an IME composition event */ public final boolean isCompositionEvent() { return COMPOSITION_EVENTS.contains(getType()); } /** * Returns true if the key event is an IME input event. * Only makes sense to call this method if this is a key signal. * Does not work on FF. (TODO(danilatos): Can it be done? Tricks * with dom mutation events?) * * @return true if this is an IME input event */ public final boolean isImeKeyEvent() { return getKeyCode() == SignalKeyLogic.IME_CODE; } /** * @return true if this is a mouse event * TODO(danilatos): Have a top level EventSignalType enum */ public final boolean isMouseEvent() { return MOUSE_EVENTS.contains(getType()); } /** * TODO(danilatos): Click + drag? I.e. return true for mouse move, if the * button is pressed? (this might be useful for tracking changing selections * as the user holds & drags) * @return true if this is an event involving some use of mouse buttons */ public final boolean isMouseButtonEvent() { return MOUSE_BUTTON_EVENTS.contains(getType()); } /** * @return true if this is a mouse event but not {@link #isMouseButtonEvent()} */ public final boolean isMouseButtonlessEvent() { return MOUSE_BUTTONLESS_EVENTS.contains(getType()); } /** * @return true if this is a "click" event */ public final boolean isClickEvent() { return "click".equals(getType()); } /** * @return True if this is a dom mutation event */ public final boolean isMutationEvent() { // What about DOMMouseScroll? return getType().startsWith("DOM"); } /** * @return true if this is any sort of clipboard event */ public final boolean isClipboardEvent() { return CLIPBOARD_EVENTS.contains(getType()); } /** * @return If this is a focus event */ public final boolean isFocusEvent() { return FOCUS_EVENTS.contains(getType()); } /** * @return true if this is a paste event * TODO(danilatos): Make a ClipboardSignalType enum instead */ public final boolean isPasteEvent() { return (UserAgent.isIE() ? "beforepaste" : "paste").equals(nativeEvent.getType()); } /** * @return true if this is a cut event * TODO(danilatos): Make a ClipboardSignalType enum instead */ public final boolean isCutEvent() { return (UserAgent.isIE() ? "beforecut" : "cut").equals(nativeEvent.getType()); } /** * @return true if this is a copy event * TODO(danilatos): Make a ClipboardSignalType enum instead */ public final boolean isCopyEvent() { return "copy".equals(nativeEvent.getType()); } /** * @return true if the command key is depressed * @see SignalKeyLogic#commandIsCtrl() */ public final boolean getCommandKey() { return logic.commandIsCtrl() ? getCtrlKey() : getMetaKey(); } public static boolean getCommandKey(com.google.gwt.dom.client.NativeEvent event) { return logic.commandIsCtrl() ? event.getCtrlKey() : event.getMetaKey(); } /** * @return true if the ctrl key is depressed */ public final boolean getCtrlKey() { return nativeEvent.getCtrlKey(); } /** * @return true if the meta key is depressed */ public final boolean getMetaKey() { return nativeEvent.getMetaKey(); } /** * @return true if the alt key is depressed */ public final boolean getAltKey() { // TODO(danilatos): Handle Alt vs Option on OSX? return nativeEvent.getAltKey(); } /** * @return true if the shift key is depressed */ public final boolean getShiftKey() { return nativeEvent.getShiftKey(); } /** * @return The underlying event view of this event */ public final Event asEvent() { return (Event) nativeEvent; } /** * Only valid for key events. * Currently only implemented for deleting, not actual navigating. * @return The move unit of this event */ public final MoveUnit getMoveUnit() { if (getKeySignalType() == KeySignalType.DELETE) { if (UserAgent.isMac()) { if (getAltKey()) { // Note: in practice, some combinations of bkspc/delete + modifier key // have no effect. This is inconsistent across browsers. It's probably // ok to normalise it here, as we will be manually implementing everything // except character-sized deletes on collapsed selections, and so users // would get a more consistent (and logical and symmetrical) experience. return MoveUnit.WORD; } else if (getCommandKey()) { return MoveUnit.LINE; } else { return MoveUnit.CHARACTER; } } else { if (getCommandKey()) { return MoveUnit.WORD; } else { return MoveUnit.CHARACTER; } } } else { // TODO(danilatos): Also implement for mere navigation events? // Currently just for deleting... so we'll at least for now just pretend // everything else is of character magnitude. This is because we // probably won't be using the information anyway, instead letting // the browser just do its default navigation behaviour. return MoveUnit.CHARACTER; } } @Override public final boolean isUndoCombo() { return isCombo('Z', KeyModifier.COMMAND); } @Override public final boolean isRedoCombo() { if ((UserAgent.isMac() || UserAgent.isLinux()) && isCombo('Z', KeyModifier.COMMAND_SHIFT)) { // Mac and Linux accept command-shift-z for undo return true; } // NOTE(user): COMMAND + Y for redo, except for Mac OS X (for chrome, // default behaviour is browser history) return !UserAgent.isMac() && isCombo('Y', KeyModifier.COMMAND); } /** * Because we must use keypress events for FF, in order to get repeats, * but prefer keydowns for combo type events for the other browsers, * we need to convert the case here. * * @param letter */ private final int comboInputKeyCode(char letter) { // TODO(danilatos): Check the compiled javascript to make sure it does simple // numerical operations and not string manipulations and conversions... char is // used all over this file return UserAgent.isFirefox() ? letter + 'a' - 'A' : letter; } /** * @param letter Treated case-insensitive, including things like '1' vs '!' * User may provide either, but upper case for letters and unshifted for * other keys is recommended * @param modifier * @return True if the given letter is pressed, and only the given modifiers. */ public final boolean isCombo(int letter, KeyModifier modifier) { assert letter > 0 && letter < shiftMappings.length; int keyCode = getKeyCode(); if (keyCode >= shiftMappings.length) { return false; } return (letter == keyCode || letter == shiftMappings[keyCode]) && modifier.check(this); } /** * @param letter * @return true, if the given letter was pressed without modifiers. Takes into * account the caps lock key being pressed (it will be as if it * weren't pressed) */ public final boolean isOnly(int letter) { return isCombo(letter, KeyModifier.NONE); } @Override public final int getMouseButton() { return nativeEvent.getButton(); } /** * @return The key signal type of this even, or null if it is not a key event * @see KeySignalType */ public KeySignalType getKeySignalType() { return this.keySignalType; } /** * @return The gwtKeyCode of this event, with some minor compatibility * adjustments */ public int getKeyCode() { return this.cachedKeyCode; } /** * Returns true if the event has effectively had its propagation stopped, since * we couldn't physically stop it due to browser quirkiness. See {@link #stopPropagation()}. */ private boolean hasBeenConsumed() { return hasBeenConsumed; } private void markAsConsumed() { hasBeenConsumed = true; } protected void cacheKeyCode(int keyCode) { this.cachedKeyCode = keyCode; } private boolean stopPropagationPreventsDefault() { if (QuirksConstants.CANCEL_BUBBLING_CANCELS_IME_COMPOSITION_AND_CONTEXTMENU) { return CANCEL_BUBBLE_QUIRKS.contains(getType()); } else { return false; } } private boolean isPreventDefaultEffective() { if (QuirksConstants.PREVENT_DEFAULT_STOPS_CONTEXTMENT) { return true; } else { String type = nativeEvent.getType(); return !type.equals("contextmenu"); } } @Override public final void stopPropagation() { if (stopPropagationPreventsDefault()) { markAsConsumed(); } else { nativeEvent.stopPropagation(); } } protected final void setup(KeySignalType signalType) { this.keySignalType = signalType; } @Override public final void preventDefault() { nativeEvent.preventDefault(); if (!isPreventDefaultEffective()) { // HACK(user): Really we would like the event to continue to propagate // and stop it immediately before reaching the top, rather than at this // point. nativeEvent.stopPropagation(); } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/client/common/util/JsoIntMap.java
api/src/main/java/org/waveprotocol/wave/client/common/util/JsoIntMap.java
/** * 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 org.waveprotocol.wave.client.common.util; import org.waveprotocol.wave.model.util.IntMap; import org.waveprotocol.wave.model.util.ReadableIntMap; import java.util.Map; /** * An implementation of IntMap<V> based on JavaScript objects. * * @author ohler@google.com (Christian Ohler) * * @param <V> type of values in the map */ public class JsoIntMap<V> implements IntMap<V> { final IntMapJsoView<V> backend = IntMapJsoView.create(); private JsoIntMap() {} public static <V> JsoIntMap<V> create() { return new JsoIntMap<V>(); } @Override public void clear() { backend.clear(); } @Override public boolean containsKey(int key) { return backend.has(key); } @Override public V getExisting(int key) { return backend.get(key); } @Override public V get(int key, V defaultValue) { if (backend.has(key)) { return backend.get(key); } else { return defaultValue; } } @Override public V get(int key) { return backend.get(key); } @Override public void put(int key, V value) { backend.put(key, value); } @Override public void putAll(ReadableIntMap<V> pairsToAdd) { // TODO(ohler): check instanceof here and implement a fallback. ((JsoIntMap<V>) pairsToAdd).backend.addToMap(this.backend); } @Override public void putAll(Map<Integer, V> pairsToAdd) { for (Map.Entry<Integer, V> e : pairsToAdd.entrySet()) { backend.put(e.getKey(), e.getValue()); } } @Override public void remove(int key) { backend.remove(key); } @Override public void each(final ProcV<V> callback) { backend.each(new ProcV<V>() { @Override public void apply(int key, V item) { callback.apply(key, item); } }); } @Override public void filter(final EntryFilter<V> filter) { backend.each(new ProcV<V>() { @Override public void apply(int key, V item) { if (filter.apply(key, item)) { // entry stays } else { backend.remove(key); } } }); } @Override public boolean isEmpty() { return backend.isEmpty(); } @Override public int countEntries() { return backend.countEntries(); } @Override public String toString() { return JsoMapStringBuilder.toString(backend); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/client/common/util/JsoMapBase.java
api/src/main/java/org/waveprotocol/wave/client/common/util/JsoMapBase.java
/** * 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 org.waveprotocol.wave.client.common.util; import com.google.gwt.core.client.JavaScriptObject; /** * Common type-independent methods for optimised JSO maps * * Designed to be subclassed, but also useful in its own right for its methods * * @author danilatos@google.com (Daniel Danilatos) */ public abstract class JsoMapBase extends JavaScriptObject { protected JsoMapBase() {} /** * Removes all entries from this map. */ public final native void clear() /*-{ for (var key in this) { delete this[key]; } }-*/; /** * Tests whether this map is empty. * * @return true if this map has no entries. */ public final native boolean isEmpty() /*-{ for (var k in this) { return false; } return true; }-*/; /** * Counts the number of entries in this map. This is a time-consuming * operation. */ public final native int countEntries() /*-{ var n = 0; for (var k in this) { n++; } return n; }-*/; }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/client/common/util/JsoMapStringBuilder.java
api/src/main/java/org/waveprotocol/wave/client/common/util/JsoMapStringBuilder.java
/** * 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 org.waveprotocol.wave.client.common.util; import org.waveprotocol.wave.model.util.IdentityMap; import org.waveprotocol.wave.model.util.ReadableIntMap; import org.waveprotocol.wave.model.util.ReadableNumberMap; import org.waveprotocol.wave.model.util.ReadableStringMap; /** * Can render each kind of JsoMapBase as a string. * */ public final class JsoMapStringBuilder implements ReadableStringMap.ProcV<Object>, ReadableIntMap.ProcV<Object>, ReadableNumberMap.ProcV<Object>, IdentityMap.ProcV<Object, Object> { /** Singleton used by statics. */ private static final JsoMapStringBuilder INSTANCE = new JsoMapStringBuilder(); /** Builder used during lifetime of each doString. */ private StringBuilder builder = null; public static String toString(IntMapJsoView<?> m) { return INSTANCE.doString(m); } public static String toString(NumberMapJsoView<?> m) { return INSTANCE.doString(m); } public static String toString(IdentityMap<?,?> m) { return INSTANCE.doString(m); } public String doString(IntMapJsoView<?> m) { builder = new StringBuilder(); builder.append("{"); m.each(this); builder.append("}"); String result = builder.toString(); builder = null; return result; } public String doString(NumberMapJsoView<?> m) { builder = new StringBuilder(); builder.append("{"); m.each(this); builder.append("}"); String result = builder.toString(); builder = null; return result; } public String doString(IdentityMap<?,?> m) { builder = new StringBuilder(); builder.append("{"); m.each(this); builder.append("}"); String result = builder.toString(); builder = null; return result; } @Override public void apply(String key, Object item) { builder.append(" " + key + ": " + item + "; "); } @Override public void apply(double key, Object item) { builder.append(" " + key + ": " + item + "; "); } @Override public void apply(int key, Object item) { builder.append(" " + key + ": " + item + "; "); } @Override public void apply(Object key, Object item) { builder.append(" " + key + ": " + item + "; "); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/client/common/util/NumberMapJsoView.java
api/src/main/java/org/waveprotocol/wave/client/common/util/NumberMapJsoView.java
/** * 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 org.waveprotocol.wave.client.common.util; import org.waveprotocol.wave.model.util.ReadableNumberMap.ProcV; import java.util.HashMap; import java.util.Map; /** * A super fast and memory efficient map (directly uses a js object as the map, * and requires only 1 object). Only allows double keys, thus taking advantage * of the "perfect hashing" of doubles with respect to javascript. * * NOTE(danilatos): Does not use hasOwnProperty semantics. So it's possible for * spurious entries to appear in the map if we're not careful. Easily fixable, * but would incur a slight performance hit (I'm now just handwaving). * * TODO(dan): Use a different version from the GWT team once it is available * * @author danilatos@google.com (Daniel Danilatos) * @param <T> Type of values in the map. Keys are always doubles. * * @deprecated use {@link org.waveprotocol.wave.model.util.NumberMap} or * {@link JsoView} instead, depending on use case */ @Deprecated public final class NumberMapJsoView<T> extends JsoMapBase { /** * A function that accepts an accumulated value, a key and the corresponding * item from the map and returns the new accumulated value. * * @see NumberMapJsoView#reduce(Object, Reduce) * @param <E> * double map's type parameter * @param <R> * The type of the value being accumulated */ public interface Reduce<E, R> { /** The function */ public R apply(R soFar, double key, E item); } /** Construct an empty NumberMap */ public static native <T> NumberMapJsoView<T> create() /*-{ return {}; }-*/; /** Construct a NumberMap from a java Map */ public static <T> NumberMapJsoView<T> fromMap(Map<Double, T> map) { NumberMapJsoView<T> doubleMap = create(); for (double key : map.keySet()) { doubleMap.put(key, map.get(key)); } return doubleMap; } protected NumberMapJsoView() { } /** * @param key * @return true if a value indexed by the given key is in the map */ public native boolean has(double key) /*-{ return this[key] !== undefined; }-*/; /** * @param key * @return The value with the given key, or null if not present */ public native T get(double key) /*-{ return this[key]; }-*/; /** * Put the value in the map at the given key. Note: Does not return the old * value. * * @param key * @param value */ public native void put(double key, T value) /*-{ this[key] = value; }-*/; /** * Remove the value with the given key from the map. Note: does not return the * old value. * * @param key */ public native void remove(double key) /*-{ delete this[key]; }-*/; /** * Same as {@link #remove(double)}, but returns what was previously there, if * anything. * * @param key * @return what was previously there or null */ public final T removeAndReturn(double key) { T val = get(key); remove(key); return val; } /** * Ruby/prototype.js style iterating idiom, using a callbak. Equivalent to a * for-each loop. TODO(danilatos): Implement break and through a la * prototype.js if needed. * * @param proc */ public final native void each(ProcV<? super T> proc) /*-{ for (var k in this) { proc. @org.waveprotocol.wave.model.util.ReadableNumberMap.ProcV::apply(DLjava/lang/Object;) (parseFloat(k), this[k]); } }-*/; /** * Same as ruby/prototype reduce. Same as functional foldl. Apply a function * to an accumulator and key/value in the map. The function returns the new * accumulated value. TODO(danilatos): Implement break and through a la * prototype.js if needed. * * @param initial * @param proc * @return The accumulated value * @param <R> * The accumulating type */ public final native <R> R reduce(R initial, Reduce<T, R> proc) /*-{ var reduction = initial; for (var k in this) { reduction = proc. @org.waveprotocol.wave.client.common.util.NumberMapJsoView.Reduce::apply(Ljava/lang/Object;DLjava/lang/Object;) (reduction, parseFloat(k), this[k]); } return reduction; }-*/; /** * Convert to a java Map */ public final Map<Double, T> toMap() { return addToMap(new HashMap<Double, T>()); } /** * Add all values to a java map. * * @param map * The map to add values to * @return The same map, for convenience. */ public final Map<Double, T> addToMap(final Map<Double, T> map) { each(new ProcV<T>() { public void apply(double key, T item) { map.put(key, item); } }); return map; } /** * Add all values to a NumberMap. * * @param map * The map to add values to * @return The same map, for convenience. */ public final NumberMapJsoView<T> addToMap(final NumberMapJsoView<T> map) { each(new ProcV<T>() { public void apply(double key, T item) { map.put(key, item); } }); return map; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/client/common/util/SignalEvent.java
api/src/main/java/org/waveprotocol/wave/client/common/util/SignalEvent.java
/** * 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 org.waveprotocol.wave.client.common.util; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.user.client.Event; /** * Attempts to bring sanity to the incredibly complex and inconsistent world of * browser events, especially with regards to key events. * * {@link SignalEventImpl} * * @author danilatos@google.com (Daniel Danilatos) */ public interface SignalEvent { /** * The "type" of key signal. The type is defined by us, based on a convenient * classification of these events. */ public enum KeySignalType { /** * Typing in the form of inputting text * * NOTE: "TAB" is treated as INPUT. */ INPUT, /** Moving around */ NAVIGATION, /** Deleting text (Backspace + Delete) */ DELETE, /** Other, like ESC or F3, that by themselves will do nothing to the document */ NOEFFECT, /** Sentinal for debugging purposes only */ SENTINAL } /** * The "movement unit" of this event. For example, on windows and linux, * holding down CTRL whilst navigating left and right with the arrow * keys moves a word at a time. Even more importantly, move units * are used for deleting text. */ public enum MoveUnit { /** A character at a time */ CHARACTER, /** A word at a time */ WORD, /** To the start or end of the line */ LINE, /** A "page" at a time */ PAGE, /** To the start or end of the document */ DOCUMENT } /** * These are the currently supported modifier combinations * * Supporting more requires tricky, browser-specific code. Go to the experiment harness * and have a look at the wonders.... */ public enum KeyModifier { /** No modifiers are pressed */ NONE { @Override public boolean check(SignalEvent event) { return !event.getShiftKey() && !event.getAltKey() && !event.getCtrlKey() && !event.getMetaKey(); } }, /** Only shift is pressed */ SHIFT { @Override public boolean check(SignalEvent event) { return event.getShiftKey() && !event.getAltKey() && !event.getCtrlKey() && !event.getMetaKey(); } }, /** Only ctrl is pressed */ CTRL { @Override public boolean check(SignalEvent event) { return !event.getShiftKey() && !event.getAltKey() && event.getCtrlKey() && !event.getMetaKey(); } }, /** Only alt is pressed */ ALT { @Override public boolean check(SignalEvent event) { return !event.getShiftKey() && event.getAltKey() && !event.getCtrlKey() && !event.getMetaKey(); } }, /** Only the meta key is pressed */ META { @Override public boolean check(SignalEvent event) { return !event.getShiftKey() && !event.getAltKey() && !event.getCtrlKey() && event.getMetaKey(); } }, /** * Only the "command" key is pressed * @see SignalEvent#COMMAND_IS_CTRL */ COMMAND { @Override public boolean check(SignalEvent event) { return COMMAND_IS_CTRL ? CTRL.check(event) : META.check(event); } }, /** Both ctrl and alt, but no others, are pressed */ CTRL_ALT { @Override public boolean check(SignalEvent event) { return !event.getShiftKey() && event.getAltKey() && event.getCtrlKey() && !event.getMetaKey(); } }, /** Both "command" and shift, but no others, are pressed */ COMMAND_SHIFT { @Override public boolean check(SignalEvent event) { // The ctrl/meta key which is NOT the command key boolean notCommandKey = COMMAND_IS_CTRL ? event.getMetaKey() : event.getCtrlKey(); return event.getShiftKey() && !event.getAltKey() && event.getCommandKey() && !notCommandKey; } } ; /** * Whether the "command" key is the control key (as opposed to the meta key). */ // TODO(danilatos): Reconcile this with the value in SignalKeyLogic. private static final boolean COMMAND_IS_CTRL = !UserAgent.isMac(); /** * Check if the given event has the enum value's modifiers pressed. * @param event * @return true if they are pressed */ public abstract boolean check(SignalEvent event); } /** * @return Event type as a string, e.g. "keypress" */ String getType(); /** * @return The target element of the event */ Element getTarget(); /** * @return true if the event is a key event * TODO(danilatos): Have a top level EventSignalType enum */ boolean isKeyEvent(); /** * @return true if it is an IME composition event */ boolean isCompositionEvent(); /** * Returns true if the key event is an IME input event. * Only makes sense to call this method if this is a key signal. * Does not work on FF. (TODO(danilatos): Can it be done? Tricks * with dom mutation events?) * * @return true if this is an IME input event */ boolean isImeKeyEvent(); /** * @return true if this is a mouse event * TODO(danilatos): Have a top level EventSignalType enum */ boolean isMouseEvent(); /** * TODO(danilatos): Click + drag? I.e. return true for mouse move, if the * button is pressed? (this might be useful for tracking changing selections * as the user holds & drags) * @return true if this is an event involving some use of mouse buttons */ boolean isMouseButtonEvent(); /** * @return true if this is a mouse event but not {@link #isMouseButtonEvent()} */ boolean isMouseButtonlessEvent(); /** * @return true if this is a "click" event */ boolean isClickEvent(); /** * @return True if this is a dom mutation event */ boolean isMutationEvent(); /** * @return true if this is any sort of clipboard event */ boolean isClipboardEvent(); /** * @return If this is a focus event */ boolean isFocusEvent(); /** * @return true if this is a paste event * TODO(danilatos): Make a ClipboardSignalType enum instead */ boolean isPasteEvent(); /** * @return true if this is a cut event * TODO(danilatos): Make a ClipboardSignalType enum instead */ boolean isCutEvent(); /** * @return true if this is a copy event * TODO(danilatos): Make a ClipboardSignalType enum instead */ boolean isCopyEvent(); /** * @return true if the command key is depressed * @see #COMMAND_IS_CTRL */ boolean getCommandKey(); /** * @return true if the ctrl key is depressed */ boolean getCtrlKey(); /** * @return true if the meta key is depressed */ boolean getMetaKey(); /** * @return true if the alt key is depressed */ boolean getAltKey(); /** * @return true if the shift key is depressed */ boolean getShiftKey(); /** * TODO(user): Deprecate this, as it breaks abstraction. Also prevent people * from casting back and forth. * * @return The underlying event view of this event */ Event asEvent(); /** * Only valid for key events. * Currently only implemented for deleting, not actual navigating. * @return The move unit of this event */ MoveUnit getMoveUnit(); /** * @return True if the event is the key combo for "undo" * NOTE(danilatos): This is the best we have at detecting undo events :( * We need even more special handling for undo done via the menu :( :( */ boolean isUndoCombo(); /** * @return True if the event is the key combo for "redo" */ boolean isRedoCombo(); /** * @param letter Treated case-insensitive, including things like '1' vs '!' * User may provide either, but upper case for letters and unshifted for * other keys is recommended * @param modifier * @return True if the given letter is pressed, and only the given modifiers. */ boolean isCombo(int letter, KeyModifier modifier); /** * @param letter * @return true, if the given letter was pressed without modifiers. Takes into * account the caps lock key being pressed (it will be as if it * weren't pressed) */ boolean isOnly(int letter); /** * @return The gwtKeyCode of this event, with some minor compatibility * adjustments */ int getKeyCode(); /** * @return the mouse button bit field for this event. The masks used to extract * individual buttons from the field are {@link NativeEvent#BUTTON_LEFT}, * {@link NativeEvent#BUTTON_MIDDLE}, and {@link NativeEvent#BUTTON_RIGHT}. */ int getMouseButton(); /** * @return The key signal type of this even, or null if it is not a key event * @see KeySignalType */ KeySignalType getKeySignalType(); /** * Prevent this event from propagating or, if that is impossible, ensures that * {@link SignalEventImpl#create(Event, boolean)} will subsequently return null * for the same corresponding event object. */ void stopPropagation(); /** * Prevents the browser from taking its default action for the given event. * Under some circumstances (see {@link SignalEventImpl#isPreventDefaultEffective} * this may also stop propagation. * * See also {@link #stopPropagation()}. */ public void preventDefault(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/client/common/util/UserAgentRuntimeProperties.java
api/src/main/java/org/waveprotocol/wave/client/common/util/UserAgentRuntimeProperties.java
/** * Copyright 2010 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 org.waveprotocol.wave.client.common.util; import com.google.common.annotations.VisibleForTesting; import org.waveprotocol.wave.model.util.Box; import com.google.gwt.core.client.GWT; /** * Class to contain run-time checks of a user-agent's capabilities. * * */ @VisibleForTesting public class UserAgentRuntimeProperties { private static final UserAgentRuntimeProperties INSTANCE = createInstance(); private static UserAgentRuntimeProperties createInstance() { return GWT.isScript() ? new UserAgentRuntimeProperties(getNativeUserAgent()) : new UserAgentRuntimeProperties(""); } @VisibleForTesting public static UserAgentRuntimeProperties get() { return INSTANCE; } private final String userAgent; private final int version; private final boolean isMac; private final boolean isWin; private final boolean isLinux; private final boolean isIe7; private final boolean isIe8; private final boolean isChrome; @VisibleForTesting public UserAgentRuntimeProperties(String userAgent) { this.userAgent = userAgent; this.version = calculateVersion(userAgent); this.isMac = calculateIsMac(userAgent); this.isWin = calculateIsWin(userAgent); this.isLinux = calculateIsLinux(userAgent); this.isIe7 = calculateIe7(userAgent); this.isIe8 = calculateIe8(userAgent); this.isChrome = calculateIsChrome(userAgent); } @VisibleForTesting public String getUserAgent() { return userAgent; } @VisibleForTesting public boolean isMac() { return isMac; } @VisibleForTesting public boolean isWin() { return isWin; } @VisibleForTesting public boolean isLinux() { return isLinux; } @VisibleForTesting public boolean isIe7() { return isIe7; } @VisibleForTesting public boolean isIe8(){ return isIe8; } @VisibleForTesting public boolean isChrome() { return isChrome; } /** * @return whether the current user agent version is at least the one given by * the method parameters. */ @VisibleForTesting public boolean isAtLeastVersion(int major, int minor) { return version >= (major * 1000 + minor); } /** * Do not use this for program logic - for debugging only. For program logic, * instead use {@link #isAtLeastVersion(int, int)} */ @VisibleForTesting public int getMajorVer() { return version / 1000; } /** * Do not use this for program logic - for debugging only. For program logic, * instead use {@link #isAtLeastVersion(int, int)} */ @VisibleForTesting public int getMinorVer() { return version % 1000; } private static native String getNativeUserAgent() /*-{ return navigator.userAgent; }-*/; private static boolean calculateIe7(String userAgent) { return userAgent.indexOf(" MSIE 7.") != -1; } private static boolean calculateIe8(String userAgent) { return userAgent.indexOf(" MSIE 8.") != -1; } private static boolean calculateIsMac(String userAgent) { return userAgent.indexOf("Mac") != -1; } private static boolean calculateIsWin(String userAgent) { return userAgent.indexOf("Windows") != -1; } private static boolean calculateIsLinux(String userAgent) { return userAgent.indexOf("Linux") != -1; } private static boolean calculateIsChrome(String userAgent) { return userAgent.indexOf("Chrome") != -1; } private static int calculateVersion(String userAgent) { if (userAgent == null || userAgent.isEmpty()) { return -1; } // TODO(user): Make this work after regex deps are fixed and don't break static rendering // // String regexps[] = {"firefox.([0-9]+).([0-9]+)", // "webkit.([0-9]+).([0-9]+)", // "msie.([0-9]+).([0-9]+)", // "minefield.([0-9]+).([0-9]+)"}; // TODO(user): Don't use "firefox" and "minefield", check Gecko rv. String names[] = {"firefox", "webkit", "msie", "minefield"}; for (String name : names) { int v = calculateVersion(name, userAgent); if (v >= 0) { return v; } } return -1; } // /** // * Matches a browser-specific regular expression against the user agent to // * obtain a version number. // * // * @param regexp The browser-specific regular expression to use // * @param userAgent The user agent string to check // * @return A version number or -1 if unknown // */ /** * Matches a browser-specific name against the user agent to obtain a version * number. * * @param name The browser-specific name to use * @param userAgent The user agent string to check * @return A version number or -1 if unknown */ private static int calculateVersion(String name, String userAgent) { int index = userAgent.toLowerCase().indexOf(name); if (index == -1) { return -1; } Box<Integer> output = Box.create(); index += name.length() + 1; if ((index = consumeDigit(index, userAgent, output)) == -1) { return -1; } int major = output.boxed; index++; if ((index = consumeDigit(index, userAgent, output)) == -1) { return -1; } int minor = output.boxed; return major * 1000 + minor; // TODO(user): Make this work after regex deps are fixed and don't break static rendering // // RegExp pattern = RegExp.compile(regexp); // MatchResult result = pattern.exec(userAgent.toLowerCase()); // if (result != null && result.getGroupCount() == 3) { // int major = Integer.parseInt(result.getGroup(1)); // int minor = Integer.parseInt(result.getGroup(2)); // return major * 1000 + minor; // } // return -1; } private static int consumeDigit(int index, String str, Box<Integer> output) { StringBuilder nb = new StringBuilder(); char c; while (index < str.length() && Character.isDigit( (c = str.charAt(index)) )) { nb.append(c); index++; } if (nb.length() == 0) { return -1; } try { output.boxed = Integer.parseInt(nb.toString()); return index; } catch (NumberFormatException e) { return -1; } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/api/src/main/java/org/waveprotocol/wave/client/common/util/UserAgentStaticProperties.java
api/src/main/java/org/waveprotocol/wave/client/common/util/UserAgentStaticProperties.java
/** * Copyright 2010 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 org.waveprotocol.wave.client.common.util; import com.google.gwt.core.client.GWT; /** * Class to allow conditional compilation for different user agents. * * All methods should return values that are known at compile time. * * * TODO(user): Should this ever be thrown in for free with GWT, rather use * their approach. A relevant thread is: * http://groups.google.com/group/Google-Web-Toolkit-Contributors/browse_thread/thread/6745dee7a85eb585/bd58d1a9f2344b34 * */ public abstract class UserAgentStaticProperties { static UserAgentStaticProperties get() { return INSTANCE; } private static final UserAgentStaticProperties INSTANCE = createInstance(); /** * Creates an instance of UserAgent. * * NOTE(danilatos): This method is designed to be statically evaluable by * the compiler, such that the compiler can determine that * only one subclass of UserAgent is ever used within a * given permutation. This is possible because * GWT.isClient() is replaced with true by the compiler, * even though it is executed normally in unit tests. * Testing the return value of GWT.create() is not adequate * because only boolean values can be statically evaluated * by the compiler at this time. * * @return an instance of UserAgent. */ private static UserAgentStaticProperties createInstance() { if (GWT.isClient()) { return GWT.create(UserAgentStaticProperties.class); } else { return new FirefoxImpl(); } } final boolean isWebkit() { return isSafari() || isMobileWebkit(); } /** * @return true iff the user agent uses mobile webkit */ final boolean isMobileWebkit() { return isAndroid() || isIPhone(); } // Default instance methods: most return false, since they are intended to be overriden. boolean isSafari() { return false; } boolean isFirefox() { return false; } boolean isIE() { return false; } boolean isAndroid() { return false; } boolean isIPhone() { return false; } // NOTE(user): Created via deferred binding public static class SafariImpl extends UserAgentStaticProperties { @Override protected boolean isSafari() { return true; } } // NOTE(user): Created via deferred binding public static class FirefoxImpl extends UserAgentStaticProperties { @Override protected boolean isFirefox() { return true; } } // NOTE(user): Created via deferred binding public static class IEImpl extends UserAgentStaticProperties { @Override protected boolean isIE() { return true; } } // NOTE(user): Created via deferred binding public static class AndroidImpl extends UserAgentStaticProperties { @Override protected boolean isAndroid() { return true; } } // NOTE(user): Created via deferred binding public static class IPhoneImpl extends UserAgentStaticProperties { @Override protected boolean isIPhone() { return true; } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/plugin/inspector/InspectorNavigationHandler.java
server/src/main/java/collide/plugin/inspector/InspectorNavigationHandler.java
package collide.plugin.inspector; import collide.gwtc.ui.GwtCompilerShell.Resources; import collide.plugin.client.inspector.InspectorPlace; import collide.plugin.client.inspector.InspectorPlace.NavigationEvent; import com.google.collide.client.AppContext; import com.google.collide.client.history.Place; import com.google.collide.client.history.PlaceNavigationHandler; import com.google.collide.client.ui.panel.MultiPanel; import com.google.collide.client.ui.panel.PanelModel; import xapi.fu.Lazy; import com.google.gwt.core.shared.GWT; public class InspectorNavigationHandler extends PlaceNavigationHandler<InspectorPlace.NavigationEvent> { private final AppContext context; private final MultiPanel<? extends PanelModel,?> contentArea; private final Place currentPlace; private final Lazy<Resources> inspectorResources; public InspectorNavigationHandler(AppContext context, MultiPanel<?,?> masterPanel, Place currentPlace) { this.context = context; this.contentArea = masterPanel; this.currentPlace = currentPlace; //create our view lazily this.inspectorResources = Lazy.deferred1(() -> { Resources res = GWT.create(Resources.class); res.gwtCompilerCss().ensureInjected(); res.gwtLogCss().ensureInjected(); res.gwtClasspathCss().ensureInjected(); res.gwtModuleCss().ensureInjected(); return res; }); } @Override public void cleanup() { contentArea.getToolBar().show(); } @Override protected void reEnterPlace(NavigationEvent navigationEvent, boolean hasNewState) { super.reEnterPlace(navigationEvent, hasNewState); } @Override protected void enterPlace(InspectorPlace.NavigationEvent navigationEvent) { contentArea.clearNavigator(); contentArea.setHeaderVisibility(false); // String module = navigationEvent.getModule(); // PanelContent panelContent = views.get(module, null); // contentArea.setContent(panelContent, // contentArea.newBuilder().setCollapseIcon(true).setClearNavigator(true).build()); contentArea.getToolBar().hide(); } public Place getCurrentPlace() { return currentPlace; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/plugin/server/IsCompileThread.java
server/src/main/java/collide/plugin/server/IsCompileThread.java
package collide.plugin.server; import collide.plugin.server.gwt.CompilerBusyException; public interface IsCompileThread <Model> { boolean isRunning(); boolean isStarted(); void kill(); void doRecompile(); void compile(String request) throws CompilerBusyException; void setContextClassLoader(ClassLoader cl); void setChannel(ClassLoader cl, Object io); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/plugin/server/AbstractCompileThread.java
server/src/main/java/collide/plugin/server/AbstractCompileThread.java
package collide.plugin.server; import collide.plugin.server.gwt.CompilerBusyException; import collide.plugin.server.gwt.CompilerRunner; import com.google.collide.dto.CodeModule; import com.google.collide.dto.CompileResponse.CompilerState; import com.google.collide.dto.server.DtoServerImpls.CompileResponseImpl; import com.google.collide.server.shared.launcher.VertxLauncher; import com.google.collide.server.shared.util.ReflectionChannel; import com.google.collide.shared.util.DebugUtil; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.net.NetServer; import io.vertx.core.net.NetSocket; import xapi.dev.gwtc.api.GwtcJob; import xapi.gwtc.api.CompiledDirectory; import com.google.gwt.core.ext.TreeLogger; import com.google.gwt.core.ext.TreeLogger.Type; import java.io.IOException; public abstract class AbstractCompileThread <CompileType extends CodeModule> extends Thread implements CompilerRunner { private static class CompileLauncher<CompileType extends CodeModule> extends VertxLauncher { private AbstractCompileThread<CompileType> thread; public CompileLauncher( AbstractCompileThread<CompileType> thread) { this.thread = thread; } @Override protected NetServer initialize(Vertx vertx, int port) { thread.port = port; return super.initialize(vertx, port); } @Override protected void handleBuffer(NetSocket event, Buffer buffer) throws IOException { thread.handleBuffer(event, buffer); } } protected ReflectionChannel io; protected boolean working = false; protected int port; protected GwtcJob controller; protected final VertxLauncher server; protected CompiledDirectory compileRequest; protected CompileResponseImpl status; protected AbstractCompileThread() { server = new CompileLauncher(this); } protected boolean isFatal(Exception e) { return true; } protected abstract void handleBuffer(NetSocket event, Buffer buffer) throws IOException; protected void initialize(Vertx vertx, int port) { //called when this compile is open for business if (status == null) return; status.setCompilerStatus(CompilerState.SERVING); status.setPort(port); io.send(status.toJson()); } protected synchronized void startOrUpdateProxy(CompiledDirectory impl, GwtcJob compiler) { this.compileRequest = impl; this.controller = compiler; System.out.println("Starting plugin thread "+getClass()); server.ensureStarted(); logger().log(Type.INFO, "Started plugin thread on port "+server.getPort()); impl.setPort(server.getPort()); } protected abstract TreeLogger logger(); @Override public void setChannel(ClassLoader cl, Object io){ this.io = new ReflectionChannel(cl, io); } @Override public void setOnDestroy(Object runOnDestroy){ assert io != null : "You must call .setChannel() before calling .setOnDestroy()." + " Called from "+DebugUtil.getCaller(); this.io.setOnDestroy(runOnDestroy); } public void compile(String request) throws CompilerBusyException{ if (working) throw new CompilerBusyException(status.getModule()); synchronized (getClass()) { if (isAlive()){ //if we're already running, we should notify so we can continue working. getClass().notify();//wake up! } working = true; if (!isAlive()){ start(); } } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/plugin/server/AbstractPluginServer.java
server/src/main/java/collide/plugin/server/AbstractPluginServer.java
package collide.plugin.server; import com.google.collide.dto.CodeModule; import com.google.collide.dto.server.DtoServerImpls.LogMessageImpl; import com.google.collide.json.shared.JsonArray; import com.google.collide.server.shared.BusModBase; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.eventbus.EventBus; import io.vertx.core.eventbus.Message; import io.vertx.core.json.JsonObject; import org.eclipse.aether.resolution.ArtifactResult; import xapi.fu.Lazy; import xapi.fu.X_Fu; import xapi.log.X_Log; import xapi.mvn.X_Maven; import xapi.util.X_Debug; import xapi.util.X_Namespace; import xapi.util.X_String; import xapi.util.api.ReceivesValue; import com.google.gwt.core.ext.TreeLogger.Type; import java.io.File; import java.io.IOException; import java.lang.management.ManagementFactory; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.security.CodeSource; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; public abstract class AbstractPluginServer // <C extends AbstractCompileThread<?>> extends BusModBase implements ServerPlugin { protected String libRoot; protected String webRoot; protected Lazy<List<String>> vertxJars = Lazy.deferred1(()->{ // TODO: load vertx version from gradle.properties... ArtifactResult artifact = X_Maven.loadArtifact("io.vertx", "vertx-core", "3.3.2"); List<String> cp = X_Maven.loadCompileDependencies(artifact.getArtifact()); // artifact = X_Maven.loadArtifact("xerces", "xercesImpl", "2.11.0"); // cp = X_Maven.loadCompileDependencies(artifact.getArtifact()); return Collections.unmodifiableList(cp); }); protected Lazy<List<String>> gwtJars = Lazy.deferred1(()->{ ArtifactResult artifact = X_Maven.loadArtifact("net.wetheinter", "gwt-dev", X_Namespace.GWT_VERSION); Set<String> cp = new LinkedHashSet<>(); cp.addAll(X_Maven.loadCompileDependencies(artifact.getArtifact())); artifact = X_Maven.loadArtifact("net.wetheinter", "gwt-user", X_Namespace.GWT_VERSION); cp.addAll(X_Maven.loadCompileDependencies(artifact.getArtifact())); artifact = X_Maven.loadArtifact("net.wetheinter", "gwt-codeserver", X_Namespace.GWT_VERSION); cp.addAll(X_Maven.loadCompileDependencies(artifact.getArtifact())); return Collections.unmodifiableList(new ArrayList<>(cp)); }); protected Lazy<List<String>> xapiGwtJar = Lazy.deferred1(()->{ ArtifactResult artifact = X_Maven.loadArtifact("net.wetheinter", "xapi-gwt", X_Namespace.XAPI_VERSION); List<String> cp = X_Maven.loadCompileDependencies(artifact.getArtifact()); return Collections.unmodifiableList(cp); }); protected Lazy<String> serverJar = Lazy.deferred1(()->{ ProtectionDomain domain = AbstractPluginServer.class.getProtectionDomain(); if (domain != null) { CodeSource source = domain.getCodeSource(); if (source != null) { URL location = source.getLocation(); if (location != null) { return location.getPath().replace("-fat", ""); } } } List<String> args = ManagementFactory.getRuntimeMXBean().getInputArguments(); for (Iterator<String> itr = args.iterator(); itr.hasNext();) { if ("-jar".equals(itr.next())) { return itr.next().replace("-fat", ""); } } throw new IllegalStateException("Unable to find server jar from runtime arguments: " + args); }); protected static final String AUTH_COOKIE_NAME = "_COLLIDE_SESSIONID"; @Override public abstract String getAddressBase(); @Override public abstract Map<String,Handler<Message<JsonObject>>> getHandlers(); @Override public void initialize(Vertx vertx) { this.eb = vertx.eventBus(); String pluginBase = getAddressBase(); for (Map.Entry<String, Handler<Message<JsonObject>>> handle : getHandlers().entrySet()){ vertx.eventBus().consumer(pluginBase+"."+handle.getKey(), handle.getValue()); } } public List<URL> getCompilerClasspath(final CodeModule request, final ReceivesValue<String> logger) { List<URL> list = new ArrayList<URL>(){ private static final long serialVersionUID = 7809897000236224683L; @Override public boolean add(URL e) { if (e==null)return false; logger.set( LogMessageImpl.make() .setLogLevel(Type.TRACE) .setMessage("Adding "+e.toExternalForm()+" to classpath") .setModule(request.getModule()) .toJson()); return super.add(e); } }; File webDir = new File(webRoot); File libDir = new File(libRoot); Set<String> dedup = new LinkedHashSet<>();//we want duplicate removal and deterministic ordering. boolean hadGwt = false; boolean hadXapi = false; // TODO add the jar containing the compiler class, if it exists on the classpath //add super-sources first (todo: implement) //add source folders for (String cp : request.getSources().asIterable()){ if (!cp.endsWith(".jar")){ URL url = toUrl(webDir,cp); if (url != null && dedup.add(url.toExternalForm())){ X_Log.debug("Adding src folder",cp, url); list.add(url); } } } //now, add all the jars listed as source for (String cp : request.getSources().asIterable()){ if (cp.endsWith(".jar")) { if (cp.contains("xapi")) { hadXapi= true; } if (cp.contains("gwt-dev")) { hadGwt = true; } URL url = toUrl(webDir,cp); if (url != null && dedup.add(url.toExternalForm())){ X_Log.debug("Adding src jar",cp, url); list.add(url);//needed for collide compile } } } String xapiVersion = System.getProperty("xapi.version", X_Namespace.XAPI_VERSION);//Hardcode X_Namespace.XAPI_VERSION for now if (!X_String.isEmpty(xapiVersion) && !hadXapi) { // only adds the uber jar if you did not depend on any xapi jars directly. // for smaller classpaths, you can specify a smaller subset of xapi dependencies; // the minimum recommended artifact to take is xapi-gwt-api. list.addAll(toUrl(dedup, xapiGwtJar.out1())); } if (!hadGwt) { list.addAll(toUrl(dedup, gwtJars.out1())); } JsonArray<String> deps = request.getDependencies(); if (deps != null) { for (String cp : deps.asIterable()){ URL url = toUrl(libDir,cp); if (url != null && dedup.add(url.toExternalForm())) { if (cp.endsWith(".jar")){ X_Log.debug("Adding dependency jar",cp, url); list.add(url);//needed for collide compile }else{ X_Log.debug("Adding dependency folder",cp, url); list.add(url);//needed for collide compile } } } try { list.add(new File(serverJar.out1()).toURI().toURL()); } catch (MalformedURLException e) { throw new RuntimeException(e); } //required to run vertx threads for (String dep : vertxJars.out1()) { try { list.add(new File(dep).toURI().toURL()); } catch (MalformedURLException e) { throw new RuntimeException(e); } } //clear our deps and put our entire resolved classpath back deps.clear(); for (URL url : list){ deps.add(url.toExternalForm().replace("file:", "")); } } X_Log.warn(getClass(), list); return list; } protected List<URL> toUrl(Set<String> dedup, List<String> strings) { return strings .stream() .map(s -> s.indexOf(":") == -1 ? "file:" + s : s ) .map(s -> { if (!dedup.add(s)) { return null; } try { return new URL(s); } catch (MalformedURLException e) { throw new RuntimeException(e); } }) .filter(X_Fu::notNull) .collect(Collectors.toList()); } public File getWebRoot() { return new File(webRoot); } public File getLibRoot() { return new File(libRoot); } @Override public void start() { super.start(); libRoot = getMandatoryStringConfig("staticFiles"); int ind = libRoot.indexOf("static"); if (ind > 0) libRoot = libRoot.substring(0, ind); libRoot = libRoot + "lib"+File.separator; webRoot = getMandatoryStringConfig("webRoot"); initialize(vertx); } protected URL toUrl(File cwd, String jar) { //TODO: allow certain whitelisted absolute uris //TODO: allow "virtual" filesystem uris, like ~/, /bin/, /lib/, /war/ String path = cwd.getAbsolutePath(); File file = new File(jar); try { if (file.exists()) { file = file.getCanonicalFile(); } else { file = new File(path, jar).getCanonicalFile(); } } catch (IOException e) { X_Log.warn(getClass(), "Error resolving canonical file for",file); } X_Log.trace(getClass(), "Resolving ",jar," to ", file); if (file.exists()){ logger.info(getClass(), "Classpath file exists: "+file); }else{ logger.warn(getClass(), "Classpath file does not exist! "+file); return null; } URI uri = URI.create("file:"+file.getAbsolutePath()); try{ return uri.toURL(); }catch (Exception e) { e.printStackTrace(); throw X_Debug.rethrow(e); } } public EventBus getEventBus() { return eb; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/plugin/server/ServerPlugin.java
server/src/main/java/collide/plugin/server/ServerPlugin.java
package collide.plugin.server; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.eventbus.Message; import io.vertx.core.json.JsonObject; import java.util.Map; public interface ServerPlugin { String getAddressBase(); /** * @return an immutable map of message handlers to hook up to vertx */ Map<String, Handler<Message<JsonObject>>>getHandlers(); void initialize(Vertx vertx); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/plugin/server/ReflectionChannelTreeLogger.java
server/src/main/java/collide/plugin/server/ReflectionChannelTreeLogger.java
package collide.plugin.server; import com.google.collide.dto.server.DtoServerImpls.LogMessageImpl; import com.google.collide.server.shared.util.ReflectionChannel; import com.google.collide.shared.util.DebugUtil; import com.google.gwt.dev.util.log.AbstractTreeLogger; import java.io.Serializable; public final class ReflectionChannelTreeLogger extends AbstractTreeLogger implements Serializable{ private static final long serialVersionUID = -8661296485728859162L; private static final String spacer = " " + ((char)160)+" " + ((char)160)+" "; private ReflectionChannel io; private String indent; private String module; public ReflectionChannelTreeLogger(ReflectionChannel io) { this(io ,"",INFO); } public ReflectionChannelTreeLogger(ReflectionChannel io, Type logLevel) { this(io ,"",logLevel); } public ReflectionChannelTreeLogger(ReflectionChannel io, String indent, Type logLevel) { this.io = io; this.indent = indent; setMaxDetail(logLevel); } @Override protected AbstractTreeLogger doBranch() { ReflectionChannelTreeLogger branch = new ReflectionChannelTreeLogger(io,indent+spacer, getMaxDetail()); branch.setModule(module); return branch; } @Override protected void doCommitBranch(AbstractTreeLogger childBeingCommitted, Type type, String msg, Throwable caught, HelpInfo helpInfo) { doLog(childBeingCommitted.getBranchedIndex(), type, msg, caught, helpInfo); } @Override protected void doLog(int indexOfLogEntryWithinParentLogger, Type type, String msg, Throwable caught, HelpInfo helpInfo) { if (getMaxDetail().ordinal()>=type.ordinal()){ System.out.println(indent+type+": "+msg+(null==caught?"":DebugUtil.getFullStacktrace(caught, "\n "))); LogMessageImpl message = LogMessageImpl.make(); message.setLogLevel(type); message.setMessage(msg); message.setModule(module); if (caught != null) message.setError(DebugUtil.getFullStacktrace(caught, "\n")); if (helpInfo != null){ message.setHelpInfo(helpInfo.getPrefix()+": "+helpInfo.getAnchorText()); } io.send(message.toJson()); } } public void setModule(String module) { this.module = module; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/plugin/server/PluginManager.java
server/src/main/java/collide/plugin/server/PluginManager.java
package collide.plugin.server; import com.google.collide.server.shared.BusModBase; import io.vertx.core.json.JsonArray; import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; public class PluginManager extends BusModBase{ Logger log = Logger.getLogger(getClass().getSimpleName()); private JsonArray plugins; @Override public void start() { super.start(); //now register all requested plugins this.plugins = getOptionalArrayConfig("plugins", new JsonArray()); Iterator<Object> iter = plugins.iterator(); while(iter.hasNext()){ Object next = iter.next(); String name = String.valueOf(next); //create the requested plugin through magic naming + reflection. //convention: package.of.PluginManager.pluginname.PluginnamePlugin.java String qualifiedName = getClass().getName().split(getClass().getSimpleName())[0]; qualifiedName = qualifiedName + name.toLowerCase()+"."+Character.toUpperCase(name.charAt(0))+name.substring(1); ServerPlugin plugin; //we're doing magic-naming lookup for plugins, //so we need to just eat & log exceptions try{ Class<?> cls; //first, try without Plugin suffix, in case packagename = classname try{ cls = Class.forName(qualifiedName, true, getClass().getClassLoader()); }catch (Exception e) { //okay, try with Plugin suffix... cls = Class.forName(qualifiedName+"Plugin", true, getClass().getClassLoader()); } Object create = cls.newInstance(); plugin = (ServerPlugin) create; }catch (Exception e) { log.log(Level.SEVERE, "Error installing plugin for "+next+". " + "Please ensure that class "+qualifiedName+" exists on classpath, " + "and that this class implements "+ServerPlugin.class.getName()); continue; } install(plugin); } } private void install(ServerPlugin plugin) { plugin.initialize(vertx); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/plugin/server/ant/AntServerPlugin.java
server/src/main/java/collide/plugin/server/ant/AntServerPlugin.java
package collide.plugin.server.ant; import collide.plugin.server.AbstractPluginServer; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.eventbus.Message; import io.vertx.core.json.JsonObject; import xapi.log.X_Log; import java.util.HashMap; import java.util.Map; @SuppressWarnings("rawtypes") public class AntServerPlugin extends AbstractPluginServer{ public class AntRunner implements Handler<Message<JsonObject>> { @Override public void handle(Message<JsonObject> event) { logger.info(event); logger.info(event.body()); X_Log.info(event); } } @Override public String getAddressBase() { return "ant"; } @Override public void initialize(Vertx vertx) { } @Override public Map<String,Handler<Message<JsonObject>>> getHandlers() { Map<String,Handler<Message<JsonObject>>> map = new HashMap<String,Handler<Message<JsonObject>>>(); //fill map from build file w/ targets...... map.put("ant", new AntRunner()); return map; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/plugin/server/gwt/CompilerBusyException.java
server/src/main/java/collide/plugin/server/gwt/CompilerBusyException.java
package collide.plugin.server.gwt; public class CompilerBusyException extends Throwable{ private static final long serialVersionUID = -7998731646049544430L; private String module; public CompilerBusyException() { } public CompilerBusyException(String module) { this.module = module; } /** * @return the module */ public String getModule() { return module; } /** * @param module the module to set */ public void setModule(String module) { this.module = module; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/plugin/server/gwt/GwtRecompileHandler.java
server/src/main/java/collide/plugin/server/gwt/GwtRecompileHandler.java
package collide.plugin.server.gwt; import java.net.URL; import java.util.ArrayList; import io.vertx.core.Handler; import io.vertx.core.eventbus.Message; import io.vertx.core.json.JsonObject; import xapi.util.api.ReceivesValue; import com.google.collide.dto.server.DtoServerImpls.GwtRecompileImpl; import com.google.collide.server.shared.util.Dto; public class GwtRecompileHandler implements Handler<Message<JsonObject>> { /** * */ private final GwtServerPlugin gwtServerPlugin; /** * @param gwtServerPlugin */ GwtRecompileHandler(GwtServerPlugin gwtServerPlugin) { this.gwtServerPlugin = gwtServerPlugin; } @Override public void handle(Message<JsonObject> message) { String jsonString = Dto.get(message); GwtRecompileImpl compileRequest = GwtRecompileImpl.fromJsonString(jsonString); GwtCompiler compiler = this.gwtServerPlugin.compilers.get(compileRequest.getModule()); // This is an initialization request, so we should create a new compile server boolean classpathMatches = compiler.isMatchingClasspath(compileRequest); if (classpathMatches) { if (compiler.isRunning()) { compiler.scheduleRecompile(); // TODO reply w/ success log } else if (compiler.isStarted()) { compiler.recompile(compileRequest.toString()); } return; } else { compiler.kill(); } // Initialize new compiler final ArrayList<String> logMessages = new ArrayList<>(); synchronized (this.gwtServerPlugin) { URL[] cp = this.gwtServerPlugin.getCompilerClasspath(compileRequest, new ReceivesValue<String>() { @Override public void set(String log) { logMessages.add(log); } }).toArray(new URL[0]); compiler.initialize(compileRequest, cp, this.gwtServerPlugin.getEventBus(), this.gwtServerPlugin.getAddressBase() + ".log", ()->{ compiler.recompile(compileRequest.toString()); for (String item : logMessages) { compiler.log(item); } }); } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/plugin/server/gwt/GwtSettingsHandler.java
server/src/main/java/collide/plugin/server/gwt/GwtSettingsHandler.java
package collide.plugin.server.gwt; import collide.shared.manifest.CollideManifest; import com.github.javaparser.ASTHelper; import com.github.javaparser.JavaParser; import com.github.javaparser.ParseException; import com.github.javaparser.ast.expr.JsonContainerExpr; import com.github.javaparser.ast.expr.JsonPairExpr; import com.github.javaparser.ast.expr.MethodCallExpr; import com.google.collide.dto.server.DtoServerImpls.GwtRecompileImpl; import com.google.collide.dto.server.DtoServerImpls.GwtSettingsImpl; import com.google.collide.server.shared.util.Dto; import io.vertx.core.Handler; import io.vertx.core.eventbus.Message; import io.vertx.core.json.JsonObject; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.resolution.ArtifactResult; import xapi.io.X_IO; import xapi.log.X_Log; import xapi.mvn.X_Maven; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; public class GwtSettingsHandler implements Handler<Message<JsonObject>> { @Override public void handle(Message<JsonObject> message) { // load up our known gwt modules GwtSettingsImpl reply = GwtSettingsImpl.make(); // Check for META-INF/collide.settings URL collideSettings = GwtSettingsHandler.class.getResource("/META-INF/collide.settings"); if (collideSettings != null) { CollideManifest manifest = new CollideManifest(""); try ( InputStream in = collideSettings.openStream(); ) { String source = X_IO.toStringUtf8(in); final JsonContainerExpr expr = JavaParser.parseJsonContainer(source); assert expr.isArray(); for (Iterator<JsonPairExpr> itr = expr.getPairs().iterator(); itr.hasNext(); ) { final JsonPairExpr pair = itr.next(); final JsonContainerExpr settings = (JsonContainerExpr) pair.getValueExpr(); List<String> modules = ASTHelper.extractStrings(settings.getNode("module")); List<String> sources = ASTHelper.extractStrings(settings.getNode("sources")); List<String> classpath = extractClasspath((JsonContainerExpr)settings.getNode("classpath")); for (String module : modules) { GwtRecompileImpl build = GwtRecompileImpl.make(); build.setModule(module); build.setSources(sources); build.setDependencies(classpath); reply.addModules(build); } } } catch (ParseException | IOException e) { X_Log.info(getClass(), "Exception reading/parsing collide.settings", e); throw new RuntimeException(e); } } // TODO: send message to @FileTree, asking for .gwt.xml files, and search for sibling .gwt.settings files... message.reply(Dto.wrap(reply)); } private List<String> extractClasspath(JsonContainerExpr classpath) { final Set<String> cp = new LinkedHashSet<>(); assert classpath.isArray(); for (JsonPairExpr pair : classpath.getPairs()) { if (pair.getValueExpr() instanceof MethodCallExpr) { MethodCallExpr method = (MethodCallExpr) pair.getValueExpr(); switch (method.getName().toLowerCase()) { case "maven": assert method.getArgs().size() == 1 : "Expect exactly 1 string argument to maven() method"; final String artifactString = ASTHelper.extractStringValue(method.getArgs().get(0)); String[] artifact = artifactString.split(":"); ArtifactResult result; switch (artifact.length) { case 3: result = X_Maven.loadArtifact(artifact[0], artifact[1], artifact[2]); break; case 4: result = X_Maven.loadArtifact(artifact[0], artifact[1], artifact[2], artifact[3]); break; case 5: result = X_Maven.loadArtifact(artifact[0], artifact[1], artifact[2], artifact[3], artifact[4]); break; default: throw new IllegalArgumentException("Malformed maven artifact; " + artifactString + " must have only 3, 4 or 5 segments"); } final Artifact a = result.getArtifact(); final List<String> dependencies = X_Maven.loadCompileDependencies(a); cp.addAll(dependencies); break; default: throw new IllegalArgumentException("Unhandled classpath method: " + method); } } else { cp.add(ASTHelper.extractStringValue(pair.getValueExpr())); } } return new ArrayList<>(cp); } public static void main(String ... a) throws ParseException { final JsonContainerExpr expr = JavaParser .parseJsonContainer("[maven(\"net.wetheinter:xapi-gwt:0.5.1-SNAPSHOT\")]"); new GwtSettingsHandler().extractClasspath(expr); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/plugin/server/gwt/CompilerRunner.java
server/src/main/java/collide/plugin/server/gwt/CompilerRunner.java
package collide.plugin.server.gwt; public interface CompilerRunner extends Runnable{ void setChannel(ClassLoader cl, Object io); void compile(String request) throws CompilerBusyException; void setOnDestroy(Object runOnDestroy); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/plugin/server/gwt/GwtTestRunHandler.java
server/src/main/java/collide/plugin/server/gwt/GwtTestRunHandler.java
package collide.plugin.server.gwt; import com.google.collide.dto.server.DtoServerImpls.GwtCompileImpl; import com.google.collide.dto.server.DtoServerImpls.LogMessageImpl; import com.google.collide.server.shared.util.Dto; import io.vertx.core.Handler; import io.vertx.core.eventbus.Message; import io.vertx.core.json.JsonObject; import xapi.bytecode.ClassFile; import xapi.dev.gwtc.api.GwtcProjectGenerator; import xapi.dev.gwtc.impl.GwtcServiceImpl; import xapi.dev.scanner.X_Scanner; import xapi.file.X_File; import xapi.gwtc.api.GwtManifest; import xapi.log.X_Log; import xapi.util.api.ReceivesValue; import com.google.gwt.core.ext.TreeLogger.Type; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; public class GwtTestRunHandler implements Handler<Message<JsonObject>> { /** * */ private final GwtServerPlugin gwtServerPlugin; /** * @param gwtServerPlugin */ GwtTestRunHandler(GwtServerPlugin gwtServerPlugin) { this.gwtServerPlugin = gwtServerPlugin; } @Override public void handle(Message<JsonObject> message) { String jsonString = Dto.get(message); GwtCompileImpl compileRequest = GwtCompileImpl.fromJsonString(jsonString); String module = compileRequest.getModule(); compileRequest.setModule(module.replace('.', '_')); compileRequest.setMessageKey(module); log(module, "Searching for tests in "+module); try { List<String> resolved = new ArrayList<String>(); for (String source : compileRequest.getSources().asIterable()) { File f = new File(source).getCanonicalFile(); if (!f.exists()) { f = new File(gwtServerPlugin.getWebRoot(), source); } if (!f.exists()) { X_Log.warn(getClass(), "Missing source", f); } resolved.add(f.getCanonicalPath()); } X_Log.info(getClass(), "new sources", resolved); compileRequest.setSources(resolved); resolved = new ArrayList<String>(); for (String source : compileRequest.getDependencies().asIterable()) { File f = new File(source).getCanonicalFile(); if (!f.exists()) { f = new File(gwtServerPlugin.getLibRoot(), source); } if (!f.exists()) { X_Log.warn(getClass(), "Missing dependency", f); } resolved.add(f.getCanonicalPath()); } X_Log.info(getClass(), "new dependencies", resolved); compileRequest.setDependencies(resolved); } catch (Exception e) { X_Log.warn(getClass(), "Error resolving canonical dependency paths for ",compileRequest, e); } GwtCompiler compiler = gwtServerPlugin.compilers.get(compileRequest.getMessageKey()); // This is an initialization request, so we should create a new compile server if (compiler.isRunning()) { compiler.kill(); } // Initialize new compiler final ArrayList<String> logMessages = new ArrayList<>(); URL[] cp; synchronized (this.gwtServerPlugin) { cp = this.gwtServerPlugin.getCompilerClasspath(compileRequest, new ReceivesValue<String>() { @Override public void set(String log) { logMessages.add(log); } }).toArray(new URL[0]); } GwtcServiceImpl impl = new GwtcServiceImpl(); URLClassLoader loader = new URLClassLoader(cp, getClass().getClassLoader()); Set<URL> paths = new LinkedHashSet<URL>(); GwtManifest manifest = compiler.resolveCompile(compileRequest); Class<?> c; final GwtcProjectGenerator project = impl.getProject(module, loader); try { c = loader.loadClass(module); project.addClass(c); log(module, "Found test class "+c.getCanonicalName()); } catch (Exception e) { X_Log.info(getClass(), "Searching for tests in ",module); for (ClassFile cls : X_Scanner.findClassesInPackage(loader, module)) { try { c = loader.loadClass(cls.getQualifiedName()); if (project.addJUnitClass(c)) { log(module, "Found test class "+c.getCanonicalName()); X_Log.info(getClass(), "Adding JUnit test class", c, cls.getResourceName()); } else { X_Log.info(getClass(), "Skipping non-JUnit test class", c, cls.getResourceName()); } } catch (Exception ex) { X_Log.warn(getClass(), "Unable to load scanned class", cls, ex); continue; } String clsName = cls.getResourceName().replace(".java", ".class"); URL location = loader.getResource(clsName); try { String loc = location.toExternalForm(); if (loc.contains("jar!")) { loc = loc.split("jar!")[0]+"jar"; } if (loc.startsWith("jar:")) { loc = loc.substring(4); } X_Log.info(getClass(), "Adding source to GwtManifest: ",loc); location = new URL(loc); paths.add(location); manifest.addSource(loc); } catch (Exception x) { X_Log.warn(getClass(), "Unable to resolve resource location of ",location," from ", clsName, x); } } } manifest.addSystemProp("gwt.usearchives=false"); manifest.setWarDir(project.getTempDir().getAbsolutePath()); compileRequest.setWarDir(X_File.createTempDir("Gwtc"+manifest.getModuleName()).getAbsolutePath()); log(module, "Generating module into "+project.getTempDir()); impl.generateCompile(manifest); project.copyModuleTo(module, manifest); String genDir = "file:"+project.getTempDir().getAbsolutePath(); try { paths.add(new URL(genDir)); X_Log.info(getClass(), "Added gen dir to classpath", genDir); } catch (MalformedURLException e) { X_Log.error(getClass(),"Malformed temp dir", genDir, e); } compileRequest.addSources(project.getTempDir().getAbsolutePath()); if (paths.size() > 0) { X_Log.info(getClass(), "Adding additional classpath elements", paths); for (URL url : paths) { compileRequest.addSources(url.toExternalForm().replace("file:", "")); } for (URL url : cp) { paths.add(url); } cp = paths.toArray(new URL[paths.size()]); } synchronized (this.gwtServerPlugin) { compiler.initialize(compileRequest, cp, this.gwtServerPlugin.getEventBus(), this.gwtServerPlugin.getAddressBase() + ".log", ()->{ log(module, "Compiling test module"); message.reply(Dto.wrap(compileRequest.toString())); X_Log.info(getClass(), "Recompiling test class:",compileRequest); compiler.recompile(compileRequest.toString()); for (String item : logMessages) { compiler.log(item); } }); X_Log.trace(getClass(), "Classpath: ", cp); } } private void log(String module, String log) { LogMessageImpl message = LogMessageImpl.make(); message.setLogLevel(Type.INFO); message.setMessage(log); message.setModule(module); gwtServerPlugin.getEventBus().send("gwt.log", Dto.wrap(message.toString())); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/plugin/server/gwt/GwtSaveHandler.java
server/src/main/java/collide/plugin/server/gwt/GwtSaveHandler.java
package collide.plugin.server.gwt; import collide.shared.manifest.CollideManifest; import com.github.javaparser.ASTHelper; import com.github.javaparser.JavaParser; import com.github.javaparser.ParseException; import com.github.javaparser.ast.exception.NotFoundException; import com.github.javaparser.ast.expr.Expression; import com.github.javaparser.ast.expr.JsonContainerExpr; import com.github.javaparser.ast.expr.JsonPairExpr; import com.google.collide.dto.server.DtoServerImpls.GwtRecompileImpl; import com.google.collide.server.shared.util.DtoManifestUtil; import com.google.common.base.Charsets; import com.google.common.io.Files; import io.vertx.core.Handler; import io.vertx.core.eventbus.Message; import io.vertx.core.json.JsonObject; import xapi.gwtc.api.GwtManifest; import xapi.io.X_IO; import xapi.log.X_Log; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Iterator; public class GwtSaveHandler implements Handler<Message<JsonObject>>{ @Override public void handle(Message<JsonObject> message) { // extract the saved compiler settings GwtRecompileImpl impl = GwtRecompileImpl.fromJsonString(message.body().toString()); GwtManifest gwtc = DtoManifestUtil.newGwtManifest(impl); // Check for META-INF/collide.settings URL collideSettings = GwtSettingsHandler.class.getResource("/META-INF/collide.settings"); JsonContainerExpr settings; final JsonContainerExpr expr; if (collideSettings != null) { CollideManifest manifest = new CollideManifest(""); boolean found = false; try ( InputStream in = collideSettings.openStream(); ) { String source = X_IO.toStringUtf8(in); expr = JavaParser.parseJsonContainer(source); assert expr.isArray(); for (Iterator<JsonPairExpr> itr = expr.getPairs().iterator(); itr.hasNext(); ) { final JsonPairExpr pair = itr.next(); settings = (JsonContainerExpr) pair.getValueExpr(); Expression module = settings.getNode("module"); if (module instanceof JsonContainerExpr) { for (JsonPairExpr mod : ((JsonContainerExpr)module).getPairs()) { if (impl.getModule().equals(ASTHelper.extractStringValue(mod.getValueExpr()))) { itr.remove(); found = true; break; } } } else { if (impl.getModule().equals(ASTHelper.extractStringValue(module))) { itr.remove(); found = true; break; } } } if (!found) { throw new NotFoundException(impl.getModule()); } } catch (ParseException | IOException e) { X_Log.info(getClass(), "Exception reading/parsing collide.settings", e); throw new RuntimeException(e); } // TODO: save the manifest into the settings file. // Now put the settings back manifest.addGwtc(gwtc); try { String path = collideSettings.getFile(); File f = new File(path); if (f.exists()) { Files.write(manifest.toString(), f, Charsets.UTF_8); } else { int jarInd = f.getName().indexOf("!"); if (jarInd == -1) { // really shouldn't happen, since our classloader had to get the file from somewhere X_Log.error("File ",f.getCanonicalPath()," does not exist"); } else { X_Log.error("File ",f.getCanonicalPath()," is a jar file, which we cannot write into"); } } } catch (Exception e) { e.printStackTrace(); } } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/plugin/server/gwt/UrlAndSystemClassLoader.java
server/src/main/java/collide/plugin/server/gwt/UrlAndSystemClassLoader.java
package collide.plugin.server.gwt; import com.google.gwt.core.ext.TreeLogger; import com.google.gwt.core.ext.TreeLogger.Type; import java.net.URL; import java.net.URLClassLoader; public class UrlAndSystemClassLoader extends URLClassLoader{ boolean allowSystem = true; boolean useParent = false; private TreeLogger log; public UrlAndSystemClassLoader(URL[] urls, TreeLogger log){ super(urls,null); this.log = log; } @Override public Class<?> loadClass(String name) throws ClassNotFoundException { if (allowSystem) try{ //TODO: handle hot-swapping... return ClassLoader.getSystemClassLoader().loadClass(name); }catch (Exception e) { log.log(Type.DEBUG, "Couldn't load "+name+" from system classloader"); } try{ if (useParent) { return getClass().getClassLoader().loadClass(name); } return super.loadClass(name); }catch (Exception e) { //last resort, use our context classloader. //this is required to do stuff like launch a working vertx server in compiler thread. if (useParent) { return super.loadClass(name); } return getClass().getClassLoader().loadClass(name); } } public boolean isAllowSystem() { return allowSystem; } public void setAllowSystem(boolean allow) { allowSystem = allow; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/plugin/server/gwt/GwtCompileHandler.java
server/src/main/java/collide/plugin/server/gwt/GwtCompileHandler.java
package collide.plugin.server.gwt; import com.google.collide.dto.server.DtoServerImpls.GwtCompileImpl; import com.google.collide.server.shared.util.Dto; import io.vertx.core.Handler; import io.vertx.core.eventbus.Message; import io.vertx.core.json.JsonObject; import xapi.util.api.ReceivesValue; import java.net.URL; import java.util.ArrayList; public class GwtCompileHandler implements Handler<Message<JsonObject>> { /** * */ private final GwtServerPlugin gwtServerPlugin; /** * @param gwtServerPlugin */ GwtCompileHandler(GwtServerPlugin gwtServerPlugin) { this.gwtServerPlugin = gwtServerPlugin; } @Override public void handle(Message<JsonObject> message) { String jsonString = Dto.get(message); GwtCompileImpl compileRequest = GwtCompileImpl.fromJsonString(jsonString); GwtCompiler compiler = gwtServerPlugin.compilers.get(compileRequest.getModule()); // This is an initialization request, so we should create a new compile server if (compiler.isRunning()) { compiler.kill(); } // Initialize new compiler final ArrayList<String> logMessages = new ArrayList<>(); synchronized (this.gwtServerPlugin) { URL[] cp = this.gwtServerPlugin.getCompilerClasspath(compileRequest, new ReceivesValue<String>() { @Override public void set(String log) { logMessages.add(log); } }).toArray(new URL[0]); compiler.initialize(compileRequest, cp, this.gwtServerPlugin.getEventBus(), this.gwtServerPlugin.getAddressBase() + ".log", ()->{ compiler.compile(compileRequest); for (String item : logMessages) { compiler.log(item); } }); } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/plugin/server/gwt/GwtCompiler.java
server/src/main/java/collide/plugin/server/gwt/GwtCompiler.java
package collide.plugin.server.gwt; import collide.plugin.server.ReflectionChannelTreeLogger; import com.google.collide.dto.CodeModule; import com.google.collide.dto.server.DtoServerImpls.GwtCompileImpl; import com.google.collide.dto.server.DtoServerImpls.GwtRecompileImpl; import com.google.collide.json.shared.JsonArray; import com.google.collide.server.shared.util.DtoManifestUtil; import com.google.collide.shared.util.JsonCollections; import io.vertx.core.eventbus.EventBus; import java.security.AccessController; import java.security.PrivilegedAction; import org.apache.xerces.parsers.SAXParser; import org.apache.xerces.parsers.XIncludeParserConfiguration; import org.apache.xerces.xni.parser.XMLParserConfiguration; import xapi.dev.api.MavenLoader; import xapi.dev.impl.ReflectiveMavenLoader; import xapi.file.X_File; import xapi.fu.Do; import xapi.gwtc.api.GwtManifest; import xapi.io.api.SimpleLineReader; import xapi.log.X_Log; import xapi.shell.X_Shell; import xapi.shell.api.ShellSession; import xapi.util.X_Debug; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.Arrays; import com.google.gwt.core.ext.TreeLogger; import com.google.gwt.core.ext.TreeLogger.Type; import com.google.gwt.core.ext.UnableToCompleteException; import com.google.gwt.dev.Compiler; import com.google.gwt.dev.util.log.PrintWriterTreeLogger; public class GwtCompiler { private Object compiler; private JsonArray<String> src = JsonCollections.createArray(); private JsonArray<String> deps = JsonCollections.createArray(); private final String module; private CrossThreadVertxChannel io; private UrlAndSystemClassLoader cl; private TreeLogger log; private Method compileMethod; public GwtCompiler(String module) { this.module = module; log = new PrintWriterTreeLogger(); } public boolean isRunning() { if (compiler == null) { return false; } try { return (Boolean)compiler.getClass().getMethod("isRunning").invoke(compiler); } catch (Exception e) { throw X_Debug.rethrow(e); } } public boolean isStarted() { if (compiler == null) { return false; } try { return (Boolean)compiler.getClass().getMethod("isStarted").invoke(compiler); } catch (Exception e) { throw X_Debug.rethrow(e); } } public void kill() { if (compiler != null) { try { Class<?> cls = compiler.getClass(); cls.getMethod("kill").invoke(compiler); cls.getMethod("interrupt").invoke(compiler); Thread.sleep(100); if (isRunning()) { System.err.println("Module "+module+" did not shut down nicely; forcing a kill.\n" + "Beware that we are using Thread.stop(); if you experience deadlock, " + "you may need to restart the server."); ClassLoader cl = cls.getClassLoader(); Object ex = cl.loadClass(UnableToCompleteException.class.getName()).newInstance(); cls.getMethod("stop", Throwable.class).invoke(compiler, ex); } } catch (Exception e) { throw X_Debug.rethrow(e); } compiler = null; } } public boolean isMatchingClasspath(CodeModule code) { return matches(src, code.getSources()) && matches(deps, code.getSources()); } private boolean matches(JsonArray<String> one, JsonArray<String> two) { return JsonCollections.equals(one, two); } public void scheduleRecompile() { if (compiler != null) { try { compiler.getClass().getMethod("doRecompile").invoke(compiler); } catch (Exception e) { throw X_Debug.rethrow(e); } } } public void scheduleCompile() { if (compiler != null) { try { compiler.getClass().getMethod("doCompile").invoke(compiler); } catch (Exception e) { throw X_Debug.rethrow(e); } } } public void recompile(String request) { assert compiler != null : "You must initailize the internal compiler before calling .compile() on "+getClass().getName(); io.setOutput(request); try { compileMethod.invoke(compiler, request); } catch (Throwable e) { throw X_Debug.rethrow(e); } } public void initialize(GwtRecompileImpl compileRequest, URL[] cp, EventBus eb, String address, Do onDone) { if (cl != null) { if (!Arrays.equals(cp, cl.getURLs())) { X_Log.info(getClass(), "Resetting classloader as urls have changed"); cl = null; } } if (cl == null) { X_Log.info(getClass(), "Creating new classloader"); X_Log.trace(getClass(), "Classpath", cp); cl = new UrlAndSystemClassLoader(cp, log); if (io != null) { try { io.destroy(); } catch (Exception e) { X_Log.warn(getClass(), "Error destroying cross-thread communication channel", io, e); } io = null; } } if (io == null) { io = new CrossThreadVertxChannel(cl, eb, address) { @Override public void destroy() throws Exception { io = null; compiler = null; super.destroy(); } }; } //Thread launchThread = new Thread(()->{ // try { cl.setAllowSystem(false); //cl.setAllowSystem(false); Class<?> launcher = cl.loadClass("com.google.collide.server.shared.launcher.VertxLauncher"); //assert launcher.getClassLoader() == cl; Class<?> recompilerClass = cl.loadClass("com.google.gwt.dev.codeserver.GwtCompilerThread"); //cl.setAllowSystem(true); Class<?> stringClass = cl.loadClass(String.class.getName()); Class<?> classLoaderClass = cl.loadClass(ClassLoader.class.getName()); Class<?> objectClass = cl.loadClass(Object.class.getName()); Constructor<?> ctor = recompilerClass.getConstructor(stringClass); compiler = ctor.newInstance(module); Method method = recompilerClass.getMethod("setContextClassLoader", classLoaderClass); method.invoke(compiler, cl); method = recompilerClass.getMethod("setDaemon", boolean.class); method.invoke(compiler, true); method = recompilerClass.getMethod("setChannel", classLoaderClass, objectClass); method.invoke(compiler, getClass().getClassLoader(), io); io.setChannel(null); ReflectionChannelTreeLogger logger = new ReflectionChannelTreeLogger(io); String messageKey = compileRequest.getMessageKey() == null ? module : compileRequest.getMessageKey(); logger.setModule(messageKey); log = logger; log.log(Type.INFO, "Initialized GWT compiler for "+module); compileMethod = recompilerClass.getMethod("compile", String.class); //cl.setAllowSystem(false); cl.loadClass(XIncludeParserConfiguration.class.getName()); cl.loadClass(XMLParserConfiguration.class.getName()); cl.loadClass(SAXParser.class.getName()); onDone.getClass().getMethod("done").invoke(onDone); } catch (Exception e) { log.log(Type.ERROR, "Unable to start the GWT compiler", e); } //}); //launchThread.setContextClassLoader(cl); //launchThread.start(); } public CrossThreadVertxChannel getIO() { assert io != null : "You must call .initialize() before calling getIO() in "+getClass().getName(); return io; } public void log(String item) { log.log(Type.TRACE, item); } public void compile(GwtCompileImpl compileRequest) { GwtManifest manifest = resolveCompile(compileRequest); String programArgs = manifest.toProgramArgs(); String[] jvmArgs = manifest.toJvmArgArray(); ReflectiveMavenLoader loader = new ReflectiveMavenLoader(); String[] cp = manifest.toClasspathFullCompile(); String tmpDir = System.getProperty("java.io.tmpdir"); tmpSearch: if (tmpDir != null) { for (String jvmArg : jvmArgs) { if (jvmArg.startsWith("-Djava.io.tmpdir")) { break tmpSearch; } } String[] newArgs = new String[jvmArgs.length+1]; System.arraycopy(jvmArgs, 0, newArgs, 0, jvmArgs.length); newArgs[newArgs.length-1] = "-Djava.io.tmpdir="+tmpDir; jvmArgs = newArgs; } X_Log.info(getClass(), "Starting gwt compile", compileRequest.getModule()); X_Log.trace(compileRequest); X_Log.trace("Args: java ", jvmArgs,programArgs); X_Log.debug("Requested Classpath\n",cp); X_Log.debug("Runtime cp", ((URLClassLoader)getClass().getClassLoader()).getURLs()); ShellSession controller = X_Shell.launchJava(Compiler.class, cp, jvmArgs, programArgs.split("[ ]+")); controller.stdErr(new SimpleLineReader() { @Override public void onLine(String errLog) { doLog(errLog, Type.ERROR); } }); controller.stdOut(new SimpleLineReader() { @Override public void onLine(String logLine) { doLog(logLine, Type.INFO); } }); } public GwtManifest resolveCompile(GwtCompileImpl compileRequest) { if (compileRequest.getWarDir() == null) { File f = X_File.createTempDir("gwtc-"+compileRequest.getModule()); if (f != null) { try { compileRequest.setWarDir(f.getCanonicalPath()); } catch (IOException e) { X_Log.warn("Unable to create temporary war directory for GWT compile", "You will likely get an unwanted war folder in the directory you executed this program"); X_Debug.maybeRethrow(e); } } } if (compileRequest.getUnitCacheDir() == null) { try { File f = X_File.createTempDir("gwtc-"+compileRequest.getModule()+"UnitCache"); if (f != null) { compileRequest.setUnitCacheDir(f.getCanonicalPath()); } } catch (IOException e) { X_Log.warn("Unable to create unit cache work directory for GWT compile", "You will likely get unwanted gwtUnitcache folders in the directory you executed this program"); } } return DtoManifestUtil.newGwtManifest(compileRequest); } protected void doLog(String logLine, Type level) { int pos = logLine.indexOf('['); test: if (pos > -1) { int end = logLine.indexOf(']', pos); if (end > -1) { switch (logLine.substring(pos+1, end)) { case "ALL": level = Type.ALL; break; case "SPAM": level = Type.SPAM; break; case "DEBUG": level = Type.DEBUG; break; case "TRACE": level = Type.TRACE; break; case "INFO": level = Type.INFO; break; case "WARN": level = Type.WARN; break; case "ERROR": level = Type.ERROR; break; default: break test; } logLine = logLine.substring(end+1); } } else { if (logLine.trim().length()==0) { return; } } if (logLine.endsWith("\n")) { logLine = logLine.substring(0, logLine.length()-1); } log.log(level, logLine); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/plugin/server/gwt/GwtServerPlugin.java
server/src/main/java/collide/plugin/server/gwt/GwtServerPlugin.java
package collide.plugin.server.gwt; import collide.plugin.server.AbstractPluginServer; import com.google.common.collect.ImmutableMap; import io.vertx.core.Handler; import io.vertx.core.eventbus.Message; import io.vertx.core.json.JsonObject; import xapi.collect.api.InitMap; import xapi.collect.impl.InitMapDefault; import xapi.fu.In1Out1; import xapi.fu.Lazy; import xapi.log.X_Log; import xapi.util.X_Namespace; import java.util.HashMap; import java.util.Map; public class GwtServerPlugin extends AbstractPluginServer //<GwtCompilerThread> { public GwtServerPlugin() { if (null == System.getProperty(X_Namespace.PROPERTY_MULTITHREADED)) { int max = Runtime.getRuntime().availableProcessors()*2+2; X_Log.trace(getClass(), "Setting max threads to "+max); System.setProperty(X_Namespace.PROPERTY_MULTITHREADED, Integer.toString(max)); } } @Override public String getAddressBase() { return "gwt"; } final InitMap<String, GwtCompiler> compilers = new InitMapDefault<>( In1Out1.identity(), GwtCompiler::new); private final Lazy<Map<String, Handler<Message<JsonObject>>>> allModules = Lazy.deferred1(() -> { Map<String, Handler<Message<JsonObject>>> map = new HashMap<>(); map.put("recompile", new GwtRecompileHandler(GwtServerPlugin.this)); map.put("compile", new GwtCompileHandler(GwtServerPlugin.this)); map.put("test", new GwtTestRunHandler(GwtServerPlugin.this)); map.put("settings", new GwtSettingsHandler()); map.put("kill", new GwtKillHandle(compilers)); map.put("save", new GwtSaveHandler()); return map; }); @Override public Map<String, Handler<Message<JsonObject>>> getHandlers() { return ImmutableMap.copyOf(allModules.out1()); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/plugin/server/gwt/CrossThreadVertxChannel.java
server/src/main/java/collide/plugin/server/gwt/CrossThreadVertxChannel.java
package collide.plugin.server.gwt; import com.google.collide.dtogen.server.JsonSerializable; import com.google.collide.server.shared.util.Dto; import com.google.collide.server.shared.util.ReflectionChannel; import io.vertx.core.eventbus.EventBus; import java.util.Stack; public class CrossThreadVertxChannel extends ReflectionChannel{ private final Stack<String> jsonString = new Stack<String>(); private EventBus eb; private String address; public CrossThreadVertxChannel(ClassLoader cl, EventBus eb,String address) { super(cl, null); this.eb = eb; this.address = address; } /** * @return a json string to ease communication between threads with different classloaders. * The only time in() is called is to get the gwt compile input json, * which is an instance of @GwtRecompile * */ @Override public String receive() { if (jsonString.isEmpty()) return null; return jsonString.pop(); } public void setOutput(String next){ jsonString.push(next); } /** * @param msg - A json encoded message to send to client. * If the request message had a replyAddress, * we pipe first output as a json reply to that message. * All subsequent messages to gwt.log (this.address) */ @Override public void send(String msg) { if (msg.startsWith("_")){//this message has packed an alternate address to use. int ind = msg.indexOf('_',1); if (ind > 0){ String to = msg.substring(1,ind); eb.send(to,Dto.wrap(msg.substring(ind+1))); return; } } //sends as gwt.log eb.send(address,Dto.wrap(msg)); } public static String encode(String address, JsonSerializable message) { assert !address.contains("_") : "You may not use _ in addresses sent through CrossThreadVertxChannel"; String encoded = message.toJson(); return "_"+address+"_"+encoded; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/plugin/server/gwt/GwtKillHandle.java
server/src/main/java/collide/plugin/server/gwt/GwtKillHandle.java
package collide.plugin.server.gwt; import io.vertx.core.Handler; import io.vertx.core.eventbus.Message; import io.vertx.core.json.JsonObject; import xapi.collect.api.InitMap; import com.google.collide.dto.CompileResponse.CompilerState; import com.google.collide.dto.server.DtoServerImpls.CompileResponseImpl; import com.google.collide.dto.server.DtoServerImpls.GwtKillImpl; import com.google.collide.server.shared.util.Dto; class GwtKillHandle implements Handler<Message<JsonObject>> { private final InitMap<String, GwtCompiler> compilers; GwtKillHandle(InitMap<String, GwtCompiler> compilers) { this.compilers = compilers; } @Override public void handle(Message<JsonObject> message) { String jsonString = Dto.get(message); GwtKillImpl killRequest = GwtKillImpl.fromJsonString(jsonString); String module = killRequest.getModule(); System.err.println("Killing gwt compile " + module); if (compilers.containsKey(module)) { compilers.get(module).kill(); compilers.removeValue(killRequest.getModule()); } CompileResponseImpl reply = CompileResponseImpl.make().setModule(killRequest.getModule()).setCompilerStatus( CompilerState.UNLOADED); message.reply(Dto.wrap(reply)); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/vertx/VertxService.java
server/src/main/java/collide/vertx/VertxService.java
package collide.vertx; import collide.server.configuration.CollideOpts; import io.vertx.core.Vertx; import io.vertx.spi.cluster.hazelcast.HazelcastClusterManager; import xapi.fu.In1; import xapi.server.vertx.scope.ScopeServiceVertx; /** * Created by James X. Nelson (james @wetheinter.net) on 10/3/16. */ public interface VertxService { HazelcastClusterManager clusterManager(); Vertx vertx(); ScopeServiceVertx scope(); void initialize(CollideOpts opts, In1<VertxService> onDone); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/server/src/main/java/collide/vertx/VertxServiceImpl.java
server/src/main/java/collide/vertx/VertxServiceImpl.java
package collide.vertx; import collide.server.StartServer; import collide.server.configuration.CollideOpts; import com.hazelcast.config.Config; import io.vertx.core.Vertx; import io.vertx.core.VertxOptions; import io.vertx.core.metrics.MetricsOptions; import io.vertx.spi.cluster.hazelcast.HazelcastClusterManager; import xapi.annotation.inject.SingletonDefault; import xapi.fu.In1; import xapi.inject.X_Inject; import xapi.log.X_Log; import xapi.scope.service.ScopeService; import xapi.server.vertx.scope.ScopeServiceVertx; import xapi.time.X_Time; /** * Created by James X. Nelson (james @wetheinter.net) on 10/3/16. */ @SingletonDefault(implFor = VertxService.class) public class VertxServiceImpl implements VertxService { private static final VertxService IMPL = X_Inject.singleton(VertxService.class); private final ScopeServiceVertx scope; private Vertx vertx; private HazelcastClusterManager manager; private CollideOpts opts; public VertxServiceImpl() { scope = (ScopeServiceVertx)X_Inject.instance(ScopeService.class); } public static void service(CollideOpts opts, In1<VertxService> service) { IMPL.initialize(opts, service); } @Override public void initialize(CollideOpts opts, In1<VertxService> onDone) { this.opts = opts; final Config custerOpts = new Config("collide"); manager = new HazelcastClusterManager(custerOpts); final VertxOptions vertxOpts = new VertxOptions(); initializeOpts(opts, vertxOpts); if (opts.isClustered()) { vertxOpts.setClusterManager(manager); Vertx.clusteredVertx(vertxOpts, async->{ if (async.succeeded()) { vertx = async.result(); onDone.in(VertxServiceImpl.this); } else { X_Log.error(StartServer.class, "Failed to start node", async.cause()); throw new IllegalStateException("Vertx Unable to start", async.cause()); } }); } else { X_Time.runLater(()->{ vertx = Vertx.vertx(vertxOpts); onDone.in(this); }); } } protected void initializeOpts(CollideOpts opts, VertxOptions vertxOpts) { vertxOpts.setMetricsOptions(new MetricsOptions().setEnabled(true)); } @Override public HazelcastClusterManager clusterManager() { return manager; } @Override public Vertx vertx() { return vertx; } @Override public ScopeServiceVertx scope() { return scope; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false