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/client/src/main/java/collide/client/treeview/SelectionModel.java | client/src/main/java/collide/client/treeview/SelectionModel.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 collide.client.treeview;
import org.waveprotocol.wave.client.common.util.SignalEvent;
import collide.client.treeview.Tree.Css;
import com.google.collide.client.util.logging.Log;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.shared.JsonArray;
/*
* TODO : Since we have breadcrumbs and will soon have tabs, we don't
* need the notion of an active node that is separate from selected nodes.
*/
/**
* Selection model for selected selected nodes in a {@link Tree}.
*
* A Tree allows for multiple selected nodes with modifiers for ctrl and shift
* click driven selects.
*/
public class SelectionModel<D> {
private JsoArray<D> selectedNodes;
private final NodeDataAdapter<D> dataAdapter;
private final Css css;
public SelectionModel(NodeDataAdapter<D> dataAdapter, Css css) {
this.dataAdapter = dataAdapter;
this.css = css;
this.selectedNodes = JsoArray.create();
}
/**
* Adds the node to the selection if it isn't already there in response to a
* context selection.
*/
public boolean contextSelect(D nodeData) {
if (selectedNodes.isEmpty()) {
// There are no selected nodes. So we should select.
insertAndSelectNode(nodeData, 0, true);
return true;
}
if (!hasSameParent(selectedNodes.get(0), nodeData) || selectedNodes.size() == 1) {
return selectSingleNode(nodeData);
}
if (!selectedNodes.contains(nodeData)) {
int insertionIndex = getInsertionIndex(nodeData);
insertAndSelectNode(nodeData, insertionIndex, true);
return true;
}
return false;
}
/**
* Returns the list of selected nodes. Not a copy. So don't play fast and
* loose mutating the list outside of this API!
*/
public JsoArray<D> getSelectedNodes() {
return selectedNodes;
}
public void removeNode(D nodeData) {
selectedNodes.remove(nodeData);
}
/**
* Restores visual selection for all selected nodes tracked by the
* SelectionModel.
*/
public JsonArray<JsonArray<String>> computeSelectedPaths() {
JsoArray<JsonArray<String>> selectedPaths = JsoArray.create();
for (int i = 0, n = selectedNodes.size(); i < n; i++) {
D nodeData = selectedNodes.get(i);
selectedPaths.add(dataAdapter.getNodePath(nodeData));
}
return selectedPaths;
}
/**
* Adds the specified node to the list of selected nodes. The list of selected
* nodes is guaranteed to be sorted in the same direction that the nodes
* appear in the tree. We only allow nodes to be in the selected list that are
* peers in the tree (we do not allow selects to span multiple depths in the
* tree.
*
* Behavior: If no modifier key is depressed, the list of selected nodes will
* be set to contain just the node passed to this method.
*
* Shift select: If shift is depressed, then we attempt to do a continuous
* range select. If there exists one or more nodes in the selected nodes list,
* we test if the node falls within the list. If it does not fall within, we
* connect the contiguous range of nodes from the specified node to the
* nearest selected node. If the node falls within the list, we do a
* continuous range selection to the LAST node that was selected, not the
* closest.
*
* CTRL select: If CTRL is depressed then we simply search for the insertion
* point of the specified node in the already sorted select list. If the node
* is already present, then we remove it and unselect the node. If it was not
* present, then we insert the node at the appropriate spot in the array and
* select it.
*
* @param nodeData the node to select
* @param event the DOM event that was associated with the select trigger.
* This is needed to detect modifier keys. If {@code null} then we
* assume that we are appending to the selection and behave just like a
* CTRL-click.
* @return whether or not the select region changed at all.
*/
public boolean selectNode(D nodeData, SignalEvent event) {
if (selectedNodes.isEmpty()) {
// There are no selected nodes. So we should select.
insertAndSelectNode(nodeData, 0, true);
return true;
}
// Ensure that the node we are selecting is a child of the same
// directory of the other nodes.
if (!hasSameParent(selectedNodes.get(0), nodeData)) {
return selectSingleNode(nodeData);
}
// So we are guaranteed to have a node that is a peer of the current set of
// nodes. Now we must examine modifier keys.
if (event == null || event.getCommandKey()) {
ctrlSelect(nodeData);
return true;
} else {
if (event.getShiftKey()) {
return shiftSelect(nodeData);
}
}
// Neither a shift nor a ctrl select. So replace the contents of the
// selected list with this node.
return selectSingleNode(nodeData);
}
/**
* Clears the the current selection and selects a single node.
*
* @return returns whether or not we actually changed the selection.
*/
public boolean selectSingleNode(D nodeData) {
// This is the case where we have a single node selected, and it is the same
// one we are clicking. We do nothing in this case.
if ((selectedNodes.size() == 1) && (selectedNodes.get(0).equals(nodeData))) {
return false;
}
clearSelections();
insertAndSelectNode(nodeData, 0, true);
return true;
}
public void clearSelections() {
visuallySelect(selectedNodes, false);
selectedNodes.clear();
}
/**
* Collects all nodes in a continuous range from the start node to the end
* node (assuming that the nodes are peers) obeying the inclusion boolean
* params for the boundaries. These nodes are not allowed to be in the
* selected list.
*/
private JsoArray<D> collectRangeToSelect(
D startNode, D endNode, boolean includeStart, boolean includeEnd) {
D parentNode = dataAdapter.getParent(startNode);
// Do some debug compile sanity checking.
assert (parentNode != null) : "Null parent nmode when doing range select!";
assert (parentNode.equals(
dataAdapter.getParent(endNode))) : "Different parent nodes when doing range highlgiht!";
assert (dataAdapter.compare(startNode, endNode) <= 0) :
"Nodes are in reverse order for range select! " + dataAdapter.getNodeName(startNode) + " - "
+ dataAdapter.getNodeName(endNode);
JsoArray<D> range = JsoArray.create();
// Do a linear scan until we find the startNode.
JsonArray<D> children = dataAdapter.getChildren(parentNode);
int i = 0;
boolean adding = false;
for (int n = children.size(); i < n; i++) {
D child = children.get(i);
if (child.equals(startNode)) {
adding = true;
if (includeStart) {
range.add(child);
}
continue;
}
if (adding) {
if (child.equals(endNode)) {
if (!includeEnd) {
break;
}
range.add(child);
break;
}
range.add(child);
}
}
// Sanity check
if (i == children.size()) {
Log.error(getClass(), "Failed to find the start when doing a range selection. Start:",
startNode, " End:", endNode);
}
return range;
}
/**
* If CTRL is depressed then we simply search for the insertion point of the
* specified node in the already sorted select list. If the node is already
* present, then we remove it and unselect the node. If it was not present,
* then we insert the node at the appropriate spot in the array and select it.
*/
private void ctrlSelect(D nodeData) {
// Find the relevant spot in the list of selected nodes.
int insertionIndex = getInsertionIndex(nodeData);
// Either select or not select depending on whether or not it was
// already present in the list.
insertAndSelectNode(
nodeData, insertionIndex, !nodeData.equals(selectedNodes.get(insertionIndex)));
}
private int getInsertionIndex(D nodeData) {
int insertionIndex = 0;
while (insertionIndex < selectedNodes.size()
&& dataAdapter.compare(nodeData, selectedNodes.get(insertionIndex)) > 0) {
insertionIndex++;
}
return insertionIndex;
}
private boolean hasSameParent(D a, D b) {
D parent1 = dataAdapter.getParent(a);
D parent2 = dataAdapter.getParent(b);
return parent1 == parent2 || (parent1 != null && parent1.equals(parent2));
}
private void insertAndSelectNode(D nodeData, int insertionIndex, boolean selectingNewNode) {
// Visually represent it.
visuallySelect(nodeData, selectingNewNode);
// Update the model.
if (selectingNewNode) {
// The node was not in the list. Add it.
selectedNodes.splice(insertionIndex, 0, nodeData);
} else {
// The node was already in the list. Take it out.
selectedNodes.splice(insertionIndex, 1);
}
}
/**
* If shift is depressed, then we attempt to do a continuous range select. If
* there exists one or more nodes in the selected nodes list, we test if the
* node falls within the list. If it does not fall within, we connect the
* contiguous range of nodes from the specified node to the nearest selected
* node. If the node falls within the list, we do a continuous range selection
* to the LAST node that was selected, not the closest.
*/
private boolean shiftSelect(D nodeData) {
// We are guaranteed to have at least one node in the list.
D firstNode = selectedNodes.get(0);
D lastNode = selectedNodes.get(selectedNodes.size() - 1);
int comparisonToFirst = dataAdapter.compare(nodeData, firstNode);
int comparisonToLast = dataAdapter.compare(nodeData, lastNode);
// If it is to the left.
if (comparisonToFirst < 0) {
JsoArray<D> range = collectRangeToSelect(nodeData, firstNode, true, false);
visuallySelect(range, true);
selectedNodes = JsoArray.concat(range, selectedNodes);
return true;
}
// If it is to the right.
if (comparisonToLast > 0) {
JsoArray<D> range = collectRangeToSelect(lastNode, nodeData, false, true);
visuallySelect(range, true);
selectedNodes = JsoArray.concat(selectedNodes, range);
return true;
}
// If it is somewhere in between, or on the boundary.
if (comparisonToFirst >= 0 && comparisonToLast <= 0) {
// Clear the set of selected nodes.
clearSelections();
selectedNodes = collectRangeToSelect(nodeData, lastNode, true, true);
visuallySelect(selectedNodes, true);
return true;
}
assert false : "SelectionModel#shiftSelect(D): This should be unreachable!";
return false;
}
private void visuallySelect(D nodeData, boolean isSelected) {
TreeNodeElement<D> renderedNode = dataAdapter.getRenderedTreeNode(nodeData);
if (renderedNode != null) {
renderedNode.setSelected(isSelected, css);
}
}
private void visuallySelect(JsonArray<D> nodeDatas, boolean isSelected) {
for (int i = 0, n = nodeDatas.size(); i < n; i++) {
visuallySelect(nodeDatas.get(i), isSelected);
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/client/treeview/NodeDataAdapter.java | client/src/main/java/collide/client/treeview/NodeDataAdapter.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 collide.client.treeview;
import javax.annotation.Nonnull;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.util.JsonCollections;
/**
* Simple adapter that allows the Tree to traverse (get the children of) some
* NodeData.
*
* Restrictions on the NodeData object. It must be able to provide sensible
* implementations of the abstract methods in this class. Namely:
*
* 1. Each node must be able to return a String key that is unique amongst its
* peers in the tree.
*
* 2. Each node must contain a back reference to its parent node.
*
* @param <D> The type of the data we want to traverse.
*/
public interface NodeDataAdapter<D> {
static class PathUtils {
public static <D> JsonArray<String> getNodePath(NodeDataAdapter<D> adapter, D data) {
JsonArray<String> pathArray = JsonCollections.createArray();
for (D node = data; adapter.getParent(node) != null; node = adapter.getParent(node)) {
pathArray.add(adapter.getNodeId(node));
}
pathArray.reverse();
return pathArray;
}
}
/**
* Compares two nodes for the purposes of sorting. Returns > 0 if a is larger
* than b. Returns < 0 if a is smaller than b. Returns 0 if they are the same.
*/
int compare(D a, D b);
/**
* @return true if the node has any child. The {@link #getChildren} may return
* an empty list for a node that has children, if those should be
* populated asynchronously
*/
boolean hasChildren(D data);
/**
* @return collection of child nodes
*/
JsonArray<D> getChildren(D data);
/**
* @return node ID that is unique within its peers in a given level in the
* tree
*/
String getNodeId(D data);
/**
* @return String name for the node
*/
String getNodeName(D data);
/**
* @return node data that is the supplied node's parent.
*/
D getParent(D data);
/**
* @return the rendered {@link TreeNodeElement} that is associated with the
* specified data node. If there is no rendered node in the tree, then
* {@code null} is returned.
*/
TreeNodeElement<D> getRenderedTreeNode(D data);
/**
* Mutates the supplied data by setting the name to be the supplied name
* String.
*/
void setNodeName(D data, String name);
/**
* Installs a reference to a rendered {@link TreeNodeElement}.
*/
void setRenderedTreeNode(D data, TreeNodeElement<D> renderedNode);
/**
* @return the node that should be the drag-and-drop target for the given
* node. The returned node must already be rendered.
*/
@Nonnull D getDragDropTarget(D data);
/**
* Returns an array of Strings representing the node IDs walking from the root
* of the tree to the specified node data.
*/
JsonArray<String> getNodePath(D data);
/**
* Looks up a node underneath the specified root using the specified relative
* path.
*/
D getNodeByPath(D root, JsonArray<String> relativeNodePath);
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/client/treeview/NodeRenderer.java | client/src/main/java/collide/client/treeview/NodeRenderer.java | package collide.client.treeview;
import elemental.dom.Element;
import elemental.html.SpanElement;
/**
* Flyweight renderer whose job it is to take a NodeData and construct the
* appropriate DOM structure for the tree node contents.
*
* @param <D> The type of data we want to render.
*/
public interface NodeRenderer<D> {
/**
* Takes in a {@link SpanElement} constructed via a call to
* {@link #renderNodeContents} and returns an element whose contract is that
* it contains only text corresponding to the key for the node's underlying
* data.
*
* This ofcourse depends on the structure that was generated via the call to
* {@link #renderNodeContents}.
*/
Element getNodeKeyTextContainer(SpanElement treeNodeLabel);
/**
* Constructs the label portion of a {@link TreeNodeElement}. Labels can have
* arbitrary DOM structure, with one constraint. At least one element MUST
* contain only text that corresponds to the String key for the underlying
* node's data.
*/
SpanElement renderNodeContents(D data);
/**
* Updates the node's contents to reflect the current state of the node.
*
* @param treeNode the tree node that contains the rendered node contents
*/
void updateNodeContents(TreeNodeElement<D> treeNode);
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/client/treeview/TreeNodeMutator.java | client/src/main/java/collide/client/treeview/TreeNodeMutator.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 collide.client.treeview;
import collide.client.util.Elements;
import com.google.gwt.resources.client.CssResource;
import elemental.dom.Element;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.events.KeyboardEvent;
import elemental.html.InputElement;
/**
* Utility for mutating a tree data model object backing a
* {@link TreeNodeElement}, in place in a {@link Tree}.
*/
public class TreeNodeMutator<D> {
/**
* Encapsulates all needed data to perform a mutation action.
*/
public interface MutationAction<D> {
Element getElementForMutation(TreeNodeElement<D> node);
void onBeforeMutation(TreeNodeElement<D> node);
void onMutationCommit(TreeNodeElement<D> node, String oldLabel, String newLabel);
boolean passValidation(TreeNodeElement<D> node, String newLabel);
}
/**
* BaseCss for the mutator.
*/
public interface Css extends CssResource {
String nodeNameInput();
}
private final EventListener keyListener = new EventListener() {
@Override
public void handleEvent(Event evt) {
KeyboardEvent keyEvent = (KeyboardEvent) evt;
switch (keyEvent.getKeyCode()) {
case KeyboardEvent.KeyCode.ENTER:
commitIfValid(false);
break;
case KeyboardEvent.KeyCode.ESC:
cancel();
break;
default:
return;
}
evt.stopPropagation();
}
};
private final EventListener blurListener = new EventListener() {
@Override
public void handleEvent(Event evt) {
commitIfValid(false);
}
};
private static class State<D> {
final TreeNodeElement<D> node;
final MutationAction<D> callback;
final InputElement input;
final String oldLabel;
State(TreeNodeElement<D> node, MutationAction<D> callback, InputElement input,
String oldLabel) {
this.node = node;
this.callback = callback;
this.input = input;
this.oldLabel = oldLabel;
}
}
private State<D> state;
private Css css;
/**
* @param css can be null
*/
public TreeNodeMutator(Css css) {
this.css = css;
}
public boolean isMutating() {
return state != null;
}
/**
* Replaces the nodes text label with an input box to allow the user to
* rename the node.
*/
public void enterMutation(TreeNodeElement<D> node, MutationAction<D> callback) {
// If we are already mutating, return.
if (isMutating()) {
return;
}
Element element = callback.getElementForMutation(node);
if (element == null) {
return;
}
String oldLabel = element.getTextContent();
callback.onBeforeMutation(node);
// Make a temporary text input box to grab user input, and place it inside
// the label element.
InputElement input = Elements.createInputElement();
if (css != null) {
input.setClassName(css.nodeNameInput());
}
input.setType("text");
input.setValue(oldLabel);
// Wipe the content from the element.
element.setTextContent("");
// Attach the temporary input box.
element.appendChild(input);
input.focus();
input.select();
// If we hit enter, commit the action.
input.addEventListener(Event.KEYUP, keyListener, false);
// If we lose focus, commit the action.
input.addEventListener(Event.BLUR, blurListener, false);
state = new State<D>(node, callback, input, oldLabel);
}
/**
* Cancels the mutation, if any.
*/
public void cancel() {
if (!isMutating()) {
return;
}
state.input.setValue(state.oldLabel);
forceCommit();
}
/**
* Commits the current text if it passes validation, or cancels the mutation.
*/
public void forceCommit() {
commitIfValid(true);
}
private void commitIfValid(boolean forceCommit) {
if (!isMutating()) {
return;
}
State<D> oldState = state;
state = null;
// Update the node label and commit the change if it passes validation.
boolean passedValidation =
oldState.callback.passValidation(oldState.node, oldState.input.getValue());
if (passedValidation || forceCommit) {
// Disconnect the handlers first!
oldState.input.removeEventListener(Event.KEYUP, keyListener, false);
oldState.input.removeEventListener(Event.BLUR, blurListener, false);
// Detach the input box. Note that on Chrome this synchronously dispatches
// a blur event. The guard above saves us.
oldState.input.removeFromParent();
String newLabel = passedValidation ? oldState.input.getValue() : oldState.oldLabel;
oldState.callback.onMutationCommit(oldState.node, oldState.oldLabel, newLabel);
} else {
state = oldState;
state.input.focus();
state.input.select();
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/client/treeview/TreeNodeElement.java | client/src/main/java/collide/client/treeview/TreeNodeElement.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 collide.client.treeview;
import collide.client.treeview.Tree.Css;
import collide.client.util.CssUtils;
import collide.client.util.Elements;
import com.google.collide.client.util.AnimationController;
import elemental.css.CSSStyleDeclaration;
import elemental.dom.Element;
import elemental.html.DivElement;
import elemental.html.SpanElement;
import elemental.js.html.JsLIElement;
import elemental.js.html.JsUListElement;
/**
* Overlay type for the base element for a Node in the tree.
*
* Nodes with no children have no UL element.
*
* Nodes that have children, but that have never been expanded (nodes render
* lazily on expansion), have an empty UL element.
*
* <pre>
*
* <li class="treeNode">
* <div class="treeNodeBody">
* <div class="expandControl"></div><span class="treeNodeLabel"></span>
* </div>
* <ul class="childrenContainer">
* </ul>
* </li>
*
* </pre>
*
*/
public class TreeNodeElement<D> extends JsLIElement {
/**
* Creates a TreeNodeElement from some data. Should only be called by
* {@link Tree}.
*
* @param <D> the type of data
* @param dataAdapter An {@link NodeDataAdapter} that allows us to visit the
* NodeData
* @return a new {@link TreeNodeElement} created from the supplied data.
*/
static <D> TreeNodeElement<D> create(
D data, NodeDataAdapter<D> dataAdapter, NodeRenderer<D> nodeRenderer, Css css) {
// Make the node base.
@SuppressWarnings("unchecked")
TreeNodeElement<D> treeNode = (TreeNodeElement<D>) Elements.createElement("li", css.treeNode());
treeNode.setData(data);
treeNode.setRenderer(nodeRenderer);
// Associate the rendered node with the underlying model data.
dataAdapter.setRenderedTreeNode(data, treeNode);
// Attach the Tree node body.
DivElement treeNodeBody = Elements.createDivElement(css.treeNodeBody());
treeNodeBody.setAttribute("draggable", "true");
DivElement expandControl = Elements.createDivElement();
SpanElement nodeContents = nodeRenderer.renderNodeContents(data);
nodeContents.addClassName(css.treeNodeLabel());
treeNodeBody.appendChild(expandControl);
treeNodeBody.appendChild(nodeContents);
treeNode.appendChild(treeNodeBody);
treeNode.ensureChildrenContainer(dataAdapter, css);
return treeNode;
}
protected TreeNodeElement() {
}
/**
* Appends the specified child to this TreeNodeElement's child container
* element.
*
* @param child The {@link TreeNodeElement} we want to append to as a child of
* this node.
*/
public final void addChild(
NodeDataAdapter<D> dataAdapter, TreeNodeElement<D> child, Css css) {
ensureChildrenContainer(dataAdapter, css);
getChildrenContainer().appendChild(child);
}
/**
* @return The associated NodeData that is a bound to this node when it was
* rendered.
*/
public final native D getData() /*-{
return this.__nodeData;
}-*/;
/**
* Nodes with no children have no UL element, only a DIV for the Node body.
*
* @return whether or not this node has children.
*/
public final boolean hasChildrenContainer() {
int length = this.getChildren().getLength();
assert (length < 3) : "TreeNodeElement has more than 2 children of its root element!";
return (length == 2);
}
public final boolean isActive(Css css) {
return CssUtils.containsClassName(getSelectionElement(), css.active());
}
/**
* Checks whether or not this node is open.
*/
public final native boolean isOpen() /*-{
return !!this.__nodeOpen;
}-*/;
private void setOpen(Css css, boolean isOpen) {
if (isOpen != isOpen()) {
CssUtils.setClassNameEnabled(getExpandControl(), css.openedIcon(), isOpen);
CssUtils.setClassNameEnabled(getExpandControl(), css.closedIcon(), !isOpen);
setOpenImpl(isOpen);
getRenderer().updateNodeContents(this);
}
}
private native void setOpenImpl(boolean isOpen) /*-{
this.__nodeOpen = isOpen;
}-*/;
public final boolean isSelected(Css css) {
return CssUtils.containsClassName(getSelectionElement(), css.selected());
}
/**
* Makes this node into a leaf node.
*/
public final void makeLeafNode(Css css) {
getExpandControl().setClassName(css.expandControl() + " " + css.leafIcon());
if (hasChildrenContainer()) {
getChildrenContainer().removeFromParent();
}
}
/**
* Removes this node from the {@link Tree} and breaks the back reference from
* the underlying node data.
*/
public final void removeFromTree() {
removeFromParent();
}
/**
* Sets whether or not this node has the active node styling applied.
*/
public final void setActive(boolean isActive, Css css) {
// Show the selection on the element returned by the node renderer
Element selectionElement = getSelectionElement();
CssUtils.setClassNameEnabled(selectionElement, css.active(), isActive);
if (isActive) {
selectionElement.focus();
}
}
/**
* Sets whether or not this node has the selected styling applied.
*/
public final void setSelected(boolean isSelected, Css css) {
CssUtils.setClassNameEnabled(getSelectionElement(), css.selected(), isSelected);
}
/**
* Sets whether or not this node is the active drop target.
*/
public final void setIsDropTarget(boolean isDropTarget, Css css) {
CssUtils.setClassNameEnabled(this, css.isDropTarget(), isDropTarget);
}
/**
* Closes the current node. Must have children if you call this!
*
* @param css The {@link Css} instance that contains relevant selector
* names.
* @param shouldAnimate whether to do the animation or not
*/
final void closeNode(NodeDataAdapter<D> dataAdapter, Css css, AnimationController closer,
boolean shouldAnimate) {
ensureChildrenContainer(dataAdapter, css);
Element expandControl = getExpandControl();
assert (hasChildrenContainer() && CssUtils.containsClassName(expandControl,
css.expandControl())) : "Tried to close a node that didn't have an expand control";
setOpen(css, false);
Element childrenContainer = getChildrenContainer();
if (shouldAnimate) {
closer.hide(childrenContainer);
} else {
closer.hideWithoutAnimating(childrenContainer);
}
}
/**
* You should call hasChildren() before calling this method. This will throw
* an exception if a Node is a leaf node.
*
* @return The UL element containing children of this TreeNodeElement.
*/
final JsUListElement getChildrenContainer() {
return (JsUListElement) this.getChildren().item(1);
}
public final SpanElement getNodeLabel() {
return (SpanElement) getNodeBody().getChildren().item(1);
}
/**
* Expands the current node. Must have children if you call this!
*
* @param css The {@link Css} instance that contains relevant selector
* names.
* @param shouldAnimate whether to do the animation or not
*/
final void openNode(NodeDataAdapter<D> dataAdapter, Css css, AnimationController opener,
boolean shouldAnimate) {
ensureChildrenContainer(dataAdapter, css);
Element expandControl = getExpandControl();
assert (hasChildrenContainer() && CssUtils.containsClassName(expandControl,
css.expandControl())) : "Tried to open a node that didn't have an expand control";
setOpen(css, true);
Element childrenContainer = getChildrenContainer();
if (shouldAnimate) {
opener.show(childrenContainer);
} else {
opener.showWithoutAnimating(childrenContainer);
}
}
/**
* If this node does not have a children container, but has children data,
* then we coerce a children container into existence.
*/
final void ensureChildrenContainer(NodeDataAdapter<D> dataAdapter, Css css) {
if (!hasChildrenContainer()) {
D data = getData();
if (dataAdapter.hasChildren(data)) {
Element childrenContainer = Elements.createElement("ul", css.childrenContainer());
this.appendChild(childrenContainer);
childrenContainer.getStyle().setDisplay(CSSStyleDeclaration.Display.NONE);
getExpandControl().setClassName(css.expandControl() + " " + css.closedIcon());
} else {
getExpandControl().setClassName(css.expandControl() + " " + css.leafIcon());
}
}
}
private Element getExpandControl() {
return (Element)getNodeBody().getChildren().item(0);
}
/**
* @return The node body element that contains the expansion control and the
* node contents.
*/
private Element getNodeBody() {
return (Element)getChildren().item(0);
}
final Element getSelectionElement() {
return getNodeBody();
}
/**
* Stashes associate NodeData as an expando on our element, and also sets up a
* reverse mapping.
*
* @param data The NodeData we want to associate with this node element.
*/
private native void setData(D data) /*-{
this.__nodeData = data;
}-*/;
private native NodeRenderer<D> getRenderer() /*-{
return this.__nodeRenderer;
}-*/;
private native void setRenderer(NodeRenderer<D> renderer) /*-{
this.__nodeRenderer = renderer;
}-*/;
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/junit/AbstractReflectionTest.java | client/src/main/java/collide/junit/AbstractReflectionTest.java | package collide.junit;
import collide.junit.cases.ReflectionCaseNoMagic;
import static xapi.reflect.X_Reflect.magicClass;
import com.google.gwt.reflect.client.strategy.ReflectionStrategy;
@ReflectionStrategy(keepNothing=true)
@SuppressWarnings("rawtypes")
public class AbstractReflectionTest {
protected static final Class CLASS_OBJECT = magicClass(Object.class);
protected static final String METHOD_EQUALS = "equals";
protected static final String METHOD_HASHCODE = "hashCode";
protected static final String METHOD_TOSTRING = "toString";
protected static final String PRIVATE_MEMBER = "privateCall";
protected static final String PUBLIC_MEMBER = "publicCall";
protected static final String OVERRIDE_FIELD = "overrideField";
static final Class<ReflectionCaseNoMagic> NO_MAGIC = ReflectionCaseNoMagic.class;
static final Class<ReflectionCaseNoMagic.Subclass> NO_MAGIC_SUBCLASS = ReflectionCaseNoMagic.Subclass.class;
static public void fail(String message) {
if (message == null) {
throw new AssertionError();
}
throw new AssertionError(message);
}
/**
* Asserts that a condition is true. If it isn't it throws
* an AssertionFailedError with the given message.
*/
static public void assertTrue(String message, boolean condition) {
if (!condition) {
fail(message);
}
}
/**
* Asserts that a condition is true. If it isn't it throws
* an AssertionFailedError.
*/
static public void assertTrue(boolean condition) {
assertTrue(null, condition);
}
/**
* Asserts that a condition is false. If it isn't it throws
* an AssertionFailedError with the given message.
*/
static public void assertFalse(String message, boolean condition) {
assertTrue(message, !condition);
}
/**
* Asserts that a condition is false. If it isn't it throws
* an AssertionFailedError.
*/
static public void assertFalse(boolean condition) {
assertFalse(null, condition);
}
/**
* Asserts that an object isn't null. If it is
* an AssertionFailedError is thrown with the given message.
*/
static public void assertNotNull(String message, Object object) {
assertTrue(message, object != null);
}
/**
* Asserts that an object isn't null.
*/
static public void assertNotNull(Object object) {
assertNotNull(null, object);
}
/**
* Asserts that an object is null. If it isn't an {@link AssertionError} is
* thrown.
* Message contains: Expected: <null> but was: object
*
* @param object Object to check or <code>null</code>
*/
static public void assertNull(Object object) {
if (object != null) {
assertNull("Expected: <null> but was: " + object.toString(), object);
}
}
/**
* Asserts that an object is null. If it is not
* an AssertionFailedError is thrown with the given message.
*/
static public void assertNull(String message, Object object) {
assertTrue(message, object == null);
}
/**
* Asserts that two objects are equal. If they are not
* an AssertionFailedError is thrown with the given message.
*/
static public void assertEquals(String message, Object expected, Object actual) {
if (expected == null && actual == null) {
return;
}
if (expected != null && expected.equals(actual)) {
return;
}
failNotEquals(message, expected, actual);
}
/**
* Asserts that two objects are equal. If they are not
* an AssertionFailedError is thrown.
*/
static public void assertEquals(Object expected, Object actual) {
assertEquals(null, expected, actual);
}
/**
* Asserts that two Strings are equal.
*/
static public void assertEquals(String message, String expected, String actual) {
if (expected == null && actual == null) {
return;
}
if (expected != null && expected.equals(actual)) {
return;
}
String cleanMessage = message == null ? "" : message;
throw new ComparisonFailure(cleanMessage, expected, actual);
}
/**
* Asserts that two Strings are equal.
*/
static public void assertEquals(String expected, String actual) {
assertEquals(null, expected, actual);
}
/**
* Asserts that two doubles are equal concerning a delta. If they are not
* an AssertionFailedError is thrown with the given message. If the expected
* value is infinity then the delta value is ignored.
*/
static public void assertEquals(String message, double expected, double actual, double delta) {
if (Double.compare(expected, actual) == 0) {
return;
}
if (!(Math.abs(expected - actual) <= delta)) {
failNotEquals(message, new Double(expected), new Double(actual));
}
}
/**
* Asserts that two doubles are equal concerning a delta. If the expected
* value is infinity then the delta value is ignored.
*/
static public void assertEquals(double expected, double actual, double delta) {
assertEquals(null, expected, actual, delta);
}
/**
* Asserts that two floats are equal concerning a positive delta. If they
* are not an AssertionFailedError is thrown with the given message. If the
* expected value is infinity then the delta value is ignored.
*/
static public void assertEquals(String message, float expected, float actual, float delta) {
if (Float.compare(expected, actual) == 0) {
return;
}
if (!(Math.abs(expected - actual) <= delta)) {
failNotEquals(message, new Float(expected), new Float(actual));
}
}
/**
* Asserts that two floats are equal concerning a delta. If the expected
* value is infinity then the delta value is ignored.
*/
static public void assertEquals(float expected, float actual, float delta) {
assertEquals(null, expected, actual, delta);
}
/**
* Asserts that two longs are equal. If they are not
* an AssertionFailedError is thrown with the given message.
*/
static public void assertEquals(String message, long expected, long actual) {
assertEquals(message, new Long(expected), new Long(actual));
}
/**
* Asserts that two longs are equal.
*/
static public void assertEquals(long expected, long actual) {
assertEquals(null, expected, actual);
}
/**
* Asserts that two booleans are equal. If they are not
* an AssertionFailedError is thrown with the given message.
*/
static public void assertEquals(String message, boolean expected, boolean actual) {
assertEquals(message, Boolean.valueOf(expected), Boolean.valueOf(actual));
}
/**
* Asserts that two booleans are equal.
*/
static public void assertEquals(boolean expected, boolean actual) {
assertEquals(null, expected, actual);
}
/**
* Asserts that two bytes are equal. If they are not
* an AssertionFailedError is thrown with the given message.
*/
static public void assertEquals(String message, byte expected, byte actual) {
assertEquals(message, new Byte(expected), new Byte(actual));
}
/**
* Asserts that two bytes are equal.
*/
static public void assertEquals(byte expected, byte actual) {
assertEquals(null, expected, actual);
}
/**
* Asserts that two chars are equal. If they are not
* an AssertionFailedError is thrown with the given message.
*/
static public void assertEquals(String message, char expected, char actual) {
assertEquals(message, new Character(expected), new Character(actual));
}
/**
* Asserts that two chars are equal.
*/
static public void assertEquals(char expected, char actual) {
assertEquals(null, expected, actual);
}
/**
* Asserts that two shorts are equal. If they are not
* an AssertionFailedError is thrown with the given message.
*/
static public void assertEquals(String message, short expected, short actual) {
assertEquals(message, new Short(expected), new Short(actual));
}
/**
* Asserts that two shorts are equal.
*/
static public void assertEquals(short expected, short actual) {
assertEquals(null, expected, actual);
}
/**
* Asserts that two ints are equal. If they are not
* an AssertionFailedError is thrown with the given message.
*/
static public void assertEquals(String message, int expected, int actual) {
assertEquals(message, new Integer(expected), new Integer(actual));
}
/**
* Asserts that two ints are equal.
*/
static public void assertEquals(int expected, int actual) {
assertEquals(null, expected, actual);
}
private static boolean isEquals(Object expected, Object actual) {
return expected.equals(actual);
}
private static boolean equalsRegardingNull(Object expected, Object actual) {
if (expected == null) {
return actual == null;
}
return isEquals(expected, actual);
}
/**
* Asserts that two objects are <b>not</b> equals. If they are, an
* {@link AssertionError} is thrown with the given message. If
* <code>first</code> and <code>second</code> are <code>null</code>,
* they are considered equal.
*
* @param message the identifying message for the {@link AssertionError} (<code>null</code>
* okay)
* @param first first value to check
* @param second the value to check against <code>first</code>
*/
static public void assertNotEquals(String message, Object first,
Object second) {
if (equalsRegardingNull(first, second)) {
failEquals(message, first);
}
}
/**
* Asserts that two objects are <b>not</b> equals. If they are, an
* {@link AssertionError} without a message is thrown. If
* <code>first</code> and <code>second</code> are <code>null</code>,
* they are considered equal.
*
* @param first first value to check
* @param second the value to check against <code>first</code>
*/
static public void assertNotEquals(Object first, Object second) {
assertNotEquals(null, first, second);
}
private static void failEquals(String message, Object actual) {
String formatted = "Values should be different. ";
if (message != null) {
formatted = message + ". ";
}
formatted += "Actual: " + actual;
fail(formatted);
}
/**
* Asserts that two longs are <b>not</b> equals. If they are, an
* {@link AssertionError} is thrown with the given message.
*
* @param message the identifying message for the {@link AssertionError} (<code>null</code>
* okay)
* @param first first value to check
* @param second the value to check against <code>first</code>
*/
static public void assertNotEquals(String message, long first, long second) {
assertNotEquals(message, (Long) first, (Long) second);
}
/**
* Asserts that two longs are <b>not</b> equals. If they are, an
* {@link AssertionError} without a message is thrown.
*
* @param first first value to check
* @param second the value to check against <code>first</code>
*/
static public void assertNotEquals(long first, long second) {
assertNotEquals(null, first, second);
}
/**
* Asserts that two doubles or floats are <b>not</b> equal to within a positive delta.
* If they are, an {@link AssertionError} is thrown with the given
* message. If the expected value is infinity then the delta value is
* ignored. NaNs are considered equal:
* <code>assertNotEquals(Double.NaN, Double.NaN, *)</code> fails
*
* @param message the identifying message for the {@link AssertionError} (<code>null</code>
* okay)
* @param first first value to check
* @param second the value to check against <code>first</code>
* @param delta the maximum delta between <code>expected</code> and
* <code>actual</code> for which both numbers are still
* considered equal.
*/
static public void assertNotEquals(String message, double first,
double second, double delta) {
if (!doubleIsDifferent(first, second, delta)) {
failEquals(message, new Double(first));
}
}
/**
* Asserts that two doubles or floats are <b>not</b> equal to within a positive delta.
* If they are, an {@link AssertionError} is thrown. If the expected
* value is infinity then the delta value is ignored.NaNs are considered
* equal: <code>assertNotEquals(Double.NaN, Double.NaN, *)</code> fails
*
* @param first first value to check
* @param second the value to check against <code>first</code>
* @param delta the maximum delta between <code>expected</code> and
* <code>actual</code> for which both numbers are still
* considered equal.
*/
static public void assertNotEquals(double first, double second, double delta) {
assertNotEquals(null, first, second, delta);
}
static private boolean doubleIsDifferent(double d1, double d2, double delta) {
if (Double.compare(d1, d2) == 0) {
return false;
}
if ((Math.abs(d1 - d2) <= delta)) {
return false;
}
return true;
}
static public void failNotEquals(String message, Object expected, Object actual) {
fail(format(message, expected, actual));
}
public static String format(String message, Object expected, Object actual) {
String formatted = "";
if (message != null && message.length() > 0) {
formatted = message + " ";
}
return formatted + "expected:<" + expected + "> but was:<" + actual + ">";
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/junit/package-info.java | client/src/main/java/collide/junit/package-info.java | @xapi.gwtc.api.Gwtc(includeGwtXml=@xapi.annotation.compile.Resource("collide.junit.JUnits"))
package collide.junit; | java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/junit/JUnitTest.java | client/src/main/java/collide/junit/JUnitTest.java | package collide.junit;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import xapi.gwtc.api.Gwtc;
import xapi.test.Assert;
import com.google.gwt.reflect.client.strategy.ReflectionStrategy;
@ReflectionStrategy
@Gwtc(includeSource="")
public class JUnitTest {
private static boolean beforeClass;
private static boolean afterClass;
private boolean before;
private boolean after;
public JUnitTest() {
Assert.assertTrue(beforeClass);
Assert.assertFalse(before);
Assert.assertFalse(after);
Assert.assertFalse(afterClass);
}
@BeforeClass
public static void beforeClass() {
beforeClass = true;
afterClass = false;
}
@AfterClass
public static void afterClass() {
afterClass = true;
}
@Before
public void before() {
before = true;
}
@After
public void after() {
after = true;
}
@Test
public void testAfter() {
Assert.assertFalse(after);
}
@Test
public void testAfterAgain() {
// Still false; instances must not be reused.
Assert.assertFalse(after);
}
@Test
public void testAfter_SecondMethod() {
Assert.assertFalse(after);
}
@Test
public void testBeforeClass() {
Assert.assertTrue(beforeClass);
}
@Test
public void testBefore() {
Assert.assertTrue(before);
}
@Test
public void testAfterClass() {
Assert.assertFalse("AfterClass has already been called",afterClass);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/junit/ArrayTests.java | client/src/main/java/collide/junit/ArrayTests.java | package collide.junit;
import org.junit.Test;
import com.google.gwt.reflect.client.strategy.ReflectionStrategy;
import com.google.gwt.reflect.shared.GwtReflect;
import java.lang.reflect.Array;
import java.util.Arrays;
/**
* @author James X. Nelson (james@wetheinter.net, @james)
*/
@ReflectionStrategy(magicSupertypes=false, keepCodeSource=true)
public class ArrayTests extends AbstractReflectionTest {
public ArrayTests() {}
@Test
public void testSingleDimPrimitive() {
long[] longs = (long[])Array.newInstance(long.class, 5);
assertEquals(longs.length, 5);
assertEquals(longs.getClass(), long[].class);
longs[0] = 1;
Array.setLong(longs, 1, 2);
Array.setLong(longs, 2, longs[0] + 2);
Array.setLong(longs, 3, Array.getLong(longs, 2) +1);
Array.setLong(longs, 4, Array.getLength(longs));
assertTrue("Arrays not equals", Arrays.equals(longs, new long[] {1,2,3,4,5}));
}
@Test
public void testSingleDimComplex() {
long[][] longs = (long[][])Array.newInstance(long[].class, 5);
assertEquals(longs.length, 5);
assertEquals(longs[0], null);
assertEquals(longs.getClass(), long[][].class);
long[] subArr = longs[0] = new long[3];
subArr[0] = 1;
Array.setLong(subArr, 1, 2);
Array.setLong(subArr, 2, subArr[0] + 2);
Array.set(longs, 1, new long[3]);
subArr = (long[])Array.get(longs, 1);
Array.setLong(subArr, 0, 1);
subArr[1] = Array.getLong(subArr, 0) +1;
Array.setLong(subArr, 2, Array.getLength(subArr));
assertTrue("Arrays not equals", Arrays.deepEquals(longs, new long[][] {
new long[]{1,2,3},new long[]{1,2,3}, null, null, null
}));
}
@Test
public void testArrayEqualsSanity() {
long[][] arrays = new long[][]{
new long[]{1,2}, new long[]{3,4}
}
, arrays2 = new long[][]{
new long[]{0,2}, new long[]{3,4}
};
assertTrue("Arrays not equals", Arrays.deepEquals(arrays, arrays));
assertFalse("Arrays.deepEquals fail", Arrays.deepEquals(arrays, arrays2));
}
@Test
public void testSingleDimObject() {
Long[] longs = (Long[])Array.newInstance(Long.class, 5);
assertEquals(longs.length, 5);
assertEquals(longs.getClass(), Long[].class);
longs[0] = 1L;
Array.set(longs, 1, 2L);
Array.set(longs, 2, longs[0] + 2);
Array.set(longs, 3, (Long)Array.get(longs, 2) +1);
Array.set(longs, 4, new Long(Array.getLength(longs)));
assertTrue("Arrays not equals", Arrays.equals(longs, new Long[] {1L,2L,3L,4L,5L}));
}
@Test
public void testMultiDimPrimitive() {
long[][] longs = (long[][])Array.newInstance(long.class, 2, 3);
assertEquals(longs.length, 2);
assertEquals(longs[0].length, 3);
assertEquals(longs.getClass(), long[][].class);
long[] subArr = longs[0];
subArr[0] = 1;
Array.setLong(subArr, 1, 2);
Array.setLong(subArr, 2, subArr[0] + 2);
subArr = (long[])Array.get(longs, 1);
Array.setLong(subArr, 0, 1);
subArr[1] = Array.getLong(subArr, 0) +1;
Array.setLong(subArr, 2, Array.getLength(subArr));
assertTrue("Arrays not equals", Arrays.deepEquals(longs, new long[][] {
new long[]{1,2,3},new long[]{1,2,3}
}));
}
@Test
public void testMultiDimObject() {
Long[][] longs = (Long[][])Array.newInstance(Long.class, 2, 3);
assertEquals(longs.length, 2);
assertEquals(longs[0].length, 3);
assertEquals(longs.getClass(), Long[][].class);
Long[] subArr = longs[0];
subArr[0] = 1L;
Array.set(subArr, 1, 2L);
Array.set(subArr, 2, subArr[0] + 2);
subArr = (Long[])Array.get(longs, 1);
Array.set(subArr, 0, 1L);
subArr[1] = (Long)Array.get(subArr, 0) +1;
Array.set(subArr, 2, new Long(Array.getLength(subArr)));
assertTrue("Arrays erroneously inequal", Arrays.deepEquals(longs, new Long[][] {
new Long[]{1L,2L,3L},new Long[]{1L,2L,3L}
}));
assertFalse("Arrays erroneously equal", Arrays.deepEquals(longs, new Long[][] {
new Long[]{1L,2L,3L},new Long[]{0L,2L,3L}
}));
}
@Test
public void testComplexDims() {
long[][][][] longs = GwtReflect.newArray(long[][].class, 2, 3);
long[][] one = new long[0][], two = new long[1][], three = new long[2][];
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/junit/MethodTests.java | client/src/main/java/collide/junit/MethodTests.java | package collide.junit;
import collide.junit.cases.ReflectionCaseNoMagic;
import collide.junit.cases.ReflectionCaseSubclass;
import collide.junit.cases.ReflectionCaseSuperclass;
import org.junit.Test;
import static com.google.gwt.reflect.shared.GwtReflect.magicClass;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.reflect.client.ConstPool.ArrayConsts;
import com.google.gwt.reflect.client.strategy.ReflectionStrategy;
import com.google.gwt.reflect.shared.GwtReflect;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* @author James X. Nelson (james@wetheinter.net)
*/
@ReflectionStrategy(keepEverything=true)
public class MethodTests extends AbstractReflectionTest {
private static final Class<Object> CLASS_OBJECT = Object.class;
private static final Class<?> classInt = int.class;
private static final Class<?> classLit = classList();
private static final Class<ReflectionCaseSubclass> SUB_CLASS = magicClass(ReflectionCaseSubclass.class);
private static final Class<ReflectionCaseSuperclass> SUPER_CLASS = magicClass(ReflectionCaseSuperclass.class);
static {magicClass(MethodTests.class);}
private static Class<?>[] classArray() {
final Class<?>[] array = new Class<?>[]{classInt, classObject()};
return array;
}
private static final Class<?> classList(){return List.class;}
private static final Class<?> classObject(){return Object.class;}
private static final native Class<?> nativeMethod()
/*-{
return @java.util.List::class;
}-*/;
public MethodTests() {}
@Test(expected=NoSuchMethodException.class)
public void testCantAccessPrivateMethods() throws Throwable {
String preventMagicMethod = PRIVATE_MEMBER;
try {
SUPER_CLASS.getMethod(preventMagicMethod);
} catch (Throwable e) {
// GWT dev wraps it's reflection failures in InvocationTargetException :/
if (GWT.isClient() && !GWT.isScript() && e instanceof InvocationTargetException) {
throw e.getCause();
}
throw e;
}
}
@Test
public void testComplexMethodInjection() throws Exception {
List<String> list = new ArrayList<String>();
Method method = ArrayList.class.getMethod("add", Object.class);
method.invoke(list, "success");
assertEquals("success", list.get(0));
final Class<?>[] array = classArray();
method = classList().getMethod("add", array);
method.invoke(list, 0, "Success!");
assertEquals("Success!", list.get(0));
};
@Test
public void testDeclaredMethodDirectly() throws Throwable {
ReflectionCaseNoMagic superClass = new ReflectionCaseNoMagic();
assertFalse(superClass.wasPrivateCalled());
Method m = NO_MAGIC.getDeclaredMethod(PRIVATE_MEMBER);
m.setAccessible(true);
assertNotNull(m);
m.invoke(superClass);
assertTrue(superClass.wasPrivateCalled());
};
@Test
public void testDeclaredMethodInjectly() throws Throwable {
ReflectionCaseSuperclass superClass = new ReflectionCaseSuperclass();
assertFalse(superClass.publicCall);
Method m = GwtReflect.getDeclaredMethod(SUPER_CLASS, PUBLIC_MEMBER);
assertNotNull(m);
m.invoke(superClass);
assertTrue(superClass.publicCall);
}
@Test
public void testGetPublicMethodDirectly() throws Throwable {
ReflectionCaseNoMagic noMagic = new ReflectionCaseNoMagic();
Method m = NO_MAGIC.getMethod(METHOD_EQUALS, Object.class);
assertNotNull(m);
assertTrue((Boolean)m.invoke(noMagic, noMagic));
}
@Test
public void testGetPublicMethodInjectly() throws Throwable {
Method m = GwtReflect.getPublicMethod(NO_MAGIC, METHOD_EQUALS, CLASS_OBJECT);
assertNotNull(m);
assertFalse((Boolean)m.invoke(new ReflectionCaseNoMagic(), new ReflectionCaseNoMagic()));
}
@Test
public void testInvoke() throws Throwable {
ReflectionCaseNoMagic inst = new ReflectionCaseNoMagic();
assertFalse(inst.publicCall);
assertFalse(inst.wasPrivateCalled());
GwtReflect.invoke(NO_MAGIC, PUBLIC_MEMBER, ArrayConsts.EMPTY_CLASSES, inst, ArrayConsts.EMPTY_OBJECTS);
assertTrue(inst.publicCall);
assertFalse(inst.wasPrivateCalled());
GwtReflect.invoke(NO_MAGIC, PRIVATE_MEMBER, ArrayConsts.EMPTY_CLASSES, inst, ArrayConsts.EMPTY_OBJECTS);
assertTrue(inst.publicCall);
assertTrue(inst.wasPrivateCalled());
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/junit/FieldTests.java | client/src/main/java/collide/junit/FieldTests.java | package collide.junit;
import collide.junit.cases.ReflectionCaseKeepsEverything;
import collide.junit.cases.ReflectionCaseKeepsNothing;
import collide.junit.cases.ReflectionCaseNoMagic;
import collide.junit.cases.ReflectionCaseNoMagic.Subclass;
import collide.junit.cases.ReflectionCaseSimple;
import org.junit.Before;
import org.junit.Test;
import static xapi.reflect.X_Reflect.magicClass;
import com.google.gwt.reflect.client.strategy.ReflectionStrategy;
import java.lang.reflect.Field;
/**
* @author James X. Nelson (james@wetheinter.net, @james)
*/
@ReflectionStrategy(magicSupertypes=false, keepCodeSource=true)
public class FieldTests extends AbstractReflectionTest {
static final Class<ReflectionCaseSimple> c = magicClass(ReflectionCaseSimple.class);
static final Class<Primitives> PRIMITIVE_CLASS = magicClass(Primitives.class);
static final Class<Objects> OBJECTS_CLASS = magicClass(Objects.class);
static final Class<ReflectionCaseKeepsNothing> KEEPS_NONE = magicClass(ReflectionCaseKeepsNothing.class);
static final Class<ReflectionCaseKeepsEverything> KEEPS_EVERYTHING = magicClass(ReflectionCaseKeepsEverything.class);
Primitives primitives;
Objects objects;
@Before
public void initObjects() throws InstantiationException, IllegalAccessException {
primitives = PRIMITIVE_CLASS.newInstance();
objects = OBJECTS_CLASS.newInstance();
}
public static class Primitives {
public Primitives() {}
public boolean z;
public byte b;
public char c;
public short s;
public int i;
public long j;
public float f;
public double d;
}
public static class Objects {
Objects() {}
public Object L;
public Primitives P;
public final Object FINAL = null;
public Boolean Z;
public Byte B;
public Character C;
public Short S;
public Integer I;
public Long J;
public Float F;
public Double D;
}
public FieldTests() {}
@Test(expected=NullPointerException.class)
public void testObjectNullAccess() throws Exception {
Field f = OBJECTS_CLASS.getField("L");
f.get(null);
}
@Test(expected=IllegalArgumentException.class)
public void testObjectIllegalSet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("P");
f.set(objects, new Object());
}
@Test
public void testObjectLegalSet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("L");
f.set(objects, primitives);
}
/////////////////////////////////////////////////
/////////////////Booleans////////////////////////
/////////////////////////////////////////////////
@Test
public void testBooleanPrimitiveLegalUse() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("z");
assertFalse(f.getBoolean(primitives));
assertFalse((Boolean)f.get(primitives));
f.set(primitives, true);
assertTrue(f.getBoolean(primitives));
assertTrue((Boolean)f.get(primitives));
}
@Test(expected=IllegalArgumentException.class)
public void testBooleanPrimitiveIllegalGet() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getDeclaredField("z");
assertEquals(1, f.getInt(primitives));
}
@Test(expected=IllegalArgumentException.class)
public void testBooleanPrimitiveIllegalSet() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("z");
assertFalse(f.getBoolean(primitives));
assertFalse((Boolean)f.get(primitives));
f.set(primitives, 1);
}
@Test(expected=IllegalArgumentException.class)
public void testBooleanPrimitiveNullSet() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("z");
assertFalse(f.getBoolean(primitives));
assertFalse((Boolean)f.get(primitives));
f.set(primitives, (Boolean)null);
}
@Test
public void testBooleanObjectNullSet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("Z");
assertNull(f.get(objects));
objects.Z = true;
assertNotNull(f.get(objects));
f.set(objects, null);
assertNull(f.get(objects));
}
@Test(expected=IllegalArgumentException.class)
public void testBooleanObjectNullGet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("Z");
assertNull(f.get(objects));
assertFalse(f.getBoolean(objects));
}
/////////////////////////////////////////////////
///////////////////Bytes/////////////////////////
/////////////////////////////////////////////////
@Test
public void testBytePrimitiveLegalUse() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("b");
assertEquals(0, f.getByte(primitives));
assertEquals(0, ((Byte)f.get(primitives)).byteValue());
f.set(primitives, (byte)1);
assertEquals(1, f.getByte(primitives));
assertEquals(1, ((Byte)f.get(primitives)).byteValue());
}
@Test
public void testBytePrimitiveWideningLegal() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("b");
assertEquals(0, f.getByte(primitives));
assertEquals(0, f.getShort(primitives));
assertEquals(0, f.getInt(primitives));
assertEquals(0, f.getLong(primitives));
assertEquals(0f, f.getFloat(primitives));
assertEquals(0., f.getDouble(primitives));
}
@Test(expected=IllegalArgumentException.class)
public void testBytePrimitiveWidening_IllegalBoolean() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("b");
f.set(primitives, true);
assertEquals(1, f.getByte(primitives));
}
@Test(expected=IllegalArgumentException.class)
public void testBytePrimitiveWidening_IllegalChar() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("b");
f.set(primitives, 'a');
assertEquals('a', f.getByte(primitives));
}
@Test(expected=IllegalArgumentException.class)
public void testBytePrimitiveNullSet() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("b");
assertEquals(0, f.getByte(primitives));
assertEquals(0, ((Byte)f.get(primitives)).byteValue());
f.set(primitives, (Byte)null);
}
@Test(expected=IllegalArgumentException.class)
public void testBytePrimitiveIllegalGet() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getDeclaredField("b");
assertTrue(f.getBoolean(primitives));
}
@Test(expected=IllegalArgumentException.class)
public void testBytePrimitiveIllegalSet() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("b");
assertEquals(0, f.getByte(primitives));
assertEquals(0, ((Byte)f.get(primitives)).byteValue());
f.set(primitives, false);
}
@Test(expected=IllegalArgumentException.class)
public void testByteObjectIllegalGet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("B");
assertEquals((byte)0, f.getByte(objects));
}
@Test(expected=IllegalArgumentException.class)
public void testByteObjectIllegalSet_Int() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("B");
f.set(objects, (int)1);
}
@Test
public void testByteObjectNullSet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("B");
assertNull(f.get(objects));
objects.B = 1;
assertNotNull(f.get(objects));
f.set(objects, null);
assertNull(f.get(objects));
}
@Test(expected=IllegalArgumentException.class)
public void testByteObjectNullGet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("B");
assertNull(f.get(objects));
assertEquals(0, f.getByte(objects));
}
/////////////////////////////////////////////////
///////////////////Chars/////////////////////////
/////////////////////////////////////////////////
@Test
public void testCharPrimitiveLegalUse() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("c");
assertEquals(0, f.getChar(primitives));
assertEquals(0, ((Character)f.get(primitives)).charValue());
f.set(primitives, (char)1);
assertEquals(1, f.getChar(primitives));
assertEquals(1, ((Character)f.get(primitives)).charValue());
}
@Test(expected=IllegalArgumentException.class)
public void testCharPrimitiveWidening_IllegalBoolean() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("c");
f.set(primitives, true);
}
@Test(expected=IllegalArgumentException.class)
public void testCharPrimitiveWidening_IllegalNumber() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("c");
f.set(primitives, 1);
}
@Test(expected=IllegalArgumentException.class)
public void testCharPrimitiveNullSet() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("c");
assertEquals(0, f.getChar(primitives));
assertEquals(0, ((Character)f.get(primitives)).charValue());
f.set(primitives, (Character)null);
}
@Test(expected=IllegalArgumentException.class)
public void testCharPrimitiveIllegalGet() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getDeclaredField("c");
assertTrue(f.getBoolean(primitives));
}
@Test(expected=IllegalArgumentException.class)
public void testCharPrimitiveIllegalSet() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("c");
assertEquals(0, f.getChar(primitives));
assertEquals(0, ((Character)f.get(primitives)).charValue());
f.set(primitives, false);
}
@Test(expected=IllegalArgumentException.class)
public void testCharacterObjectIllegalGet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("C");
assertEquals((char)0, f.getChar(objects));
}
@Test(expected=IllegalArgumentException.class)
public void testCharacterObjectIllegalSet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("C");
f.set(objects, (int)1);
}
@Test
public void testCharacterObjectNullSet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("C");
assertNull(f.get(objects));
objects.C = 'a';
assertNotNull(f.get(objects));
f.set(objects, null);
assertNull(f.get(objects));
}
@Test(expected=IllegalArgumentException.class)
public void testCharacterObjectNullGet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("C");
assertNull(f.get(objects));
assertEquals(0, f.getChar(objects));
}
/////////////////////////////////////////////////
/////////////////Shorts//////////////////////////
/////////////////////////////////////////////////
@Test
public void testShortPrimitiveLegalUse() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("s");
assertEquals(0, f.getShort(primitives));
assertEquals(0, ((Short)f.get(primitives)).shortValue());
f.set(primitives, (short)1);
assertEquals(1, f.getShort(primitives));
assertEquals(1, ((Short)f.get(primitives)).shortValue());
f.set(primitives, new Byte((byte)1));
}
@Test
public void testShortPrimitiveLegalGet() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("s");
assertEquals(0, f.getShort(primitives));
assertEquals(0, f.getInt(primitives));
assertEquals(0, f.getLong(primitives));
assertEquals(0f, f.getFloat(primitives));
assertEquals(0., f.getDouble(primitives));
}
@Test(expected=IllegalArgumentException.class)
public void testShortPrimitiveIllegalSet_Boolean() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("s");
f.set(primitives, true);
}
@Test(expected=IllegalArgumentException.class)
public void testShortPrimitiveIllegalSet_Char() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("s");
f.set(primitives, 'a');
}
@Test(expected=IllegalArgumentException.class)
public void testShortPrimitiveIllegalSet_Null() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("s");
f.set(primitives, (Short)null);
}
@Test
public void testShortObjectLegalSet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("S");
f.set(objects, (short)1);
assertEquals((short)1, f.get(objects));
}
@Test(expected=IllegalArgumentException.class)
public void testShortObjectIllegalSet_Byte() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("S");
f.set(objects, (byte)1);
}
@Test(expected=IllegalArgumentException.class)
public void testShortObjectIllegalSet_Int() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("S");
f.set(objects, (int)1);
}
@Test(expected=IllegalArgumentException.class)
public void testShortObjectIllegalGet_Byte() throws Exception {
assertNotNull(primitives);
Field f = OBJECTS_CLASS.getField("S");
f.getByte(primitives);
}
@Test
public void testShortObjectNullSet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("S");
assertNull(f.get(objects));
objects.S = 1;
assertNotNull(f.get(objects));
f.set(objects, null);
assertNull(f.get(objects));
}
@Test(expected=IllegalArgumentException.class)
public void testShortObjectNullGet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("S");
assertNull(f.get(objects));
assertEquals(0, f.getShort(objects));
}
/////////////////////////////////////////////////
////////////////////Ints/////////////////////////
/////////////////////////////////////////////////
@Test
public void testIntPrimitiveLegalUse() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("i");
assertEquals(0, f.getInt(primitives));
assertEquals(0, ((Integer) f.get(primitives)).intValue());
f.set(primitives, (int) 1);
assertEquals(1, f.getInt(primitives));
assertEquals(1, ((Integer) f.get(primitives)).intValue());
f.set(primitives, 'a');
f.set(primitives, (byte) 1);
}
@Test
public void testIntPrimitiveLegalGet() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("i");
assertEquals(0, f.getInt(primitives));
assertEquals(0, f.getLong(primitives));
assertEquals(0f, f.getFloat(primitives));
assertEquals(0., f.getDouble(primitives));
}
@Test(expected = IllegalArgumentException.class)
public void testIntPrimitiveIllegalGet_Byte() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("i");
f.getByte(primitives);
}
@Test(expected = IllegalArgumentException.class)
public void testIntPrimitiveIllegalGet_Short() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("i");
f.getShort(primitives);
}
@Test(expected = IllegalArgumentException.class)
public void testIntPrimitiveIllegalSet_Boolean() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("i");
f.set(primitives, true);
}
@Test(expected = IllegalArgumentException.class)
public void testIntPrimitiveIllegalSet_Null() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("i");
f.set(primitives, (Short) null);
}
@Test(expected = IllegalArgumentException.class)
public void testIntegerObjectIllegalSet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("I");
f.set(objects, (short)1);
}
@Test
public void testIntegerObjectNullSet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("I");
assertNull(f.get(objects));
objects.I = 1;
assertNotNull(f.get(objects));
f.set(objects, null);
assertNull(f.get(objects));
}
@Test(expected = IllegalArgumentException.class)
public void testIntegerObjectNullGet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("I");
assertNull(f.get(objects));
assertEquals(0, f.getInt(objects));
}
/////////////////////////////////////////////////
///////////////////Longs/////////////////////////
/////////////////////////////////////////////////
@Test
public void testLongPrimitiveLegalUse() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("j");
assertEquals(0, f.getLong(primitives));
assertEquals(0, ((Long) f.get(primitives)).longValue());
f.set(primitives, (long) 1);
assertEquals(1, f.getLong(primitives));
assertEquals(1, ((Long) f.get(primitives)).longValue());
f.set(primitives, 'a');
f.set(primitives, (byte) 1);
}
@Test
public void testLongPrimitiveLegalGet() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("j");
assertEquals(0, f.getLong(primitives));
assertEquals(0f, f.getFloat(primitives));
assertEquals(0., f.getDouble(primitives));
}
@Test(expected = IllegalArgumentException.class)
public void testLongPrimitiveIllegalGet_Byte() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("j");
f.getByte(primitives);
}
@Test(expected = IllegalArgumentException.class)
public void testLongPrimitiveIllegalGet_Short() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("j");
f.getShort(primitives);
}
@Test(expected = IllegalArgumentException.class)
public void testLongPrimitiveIllegalGet_Int() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("j");
f.getInt(primitives);
}
@Test(expected = IllegalArgumentException.class)
public void testLongPrimitiveIllegalSet_Boolean() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("j");
f.set(primitives, true);
}
@Test(expected = IllegalArgumentException.class)
public void testLongPrimitiveIllegalSet_Null() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("j");
f.set(primitives, (Short) null);
}
@Test(expected = IllegalArgumentException.class)
public void testLongObjectIllegalSet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("J");
f.set(objects, (int) 1);
}
@Test
public void testLongObjectNullSet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("J");
assertNull(f.get(objects));
objects.J = 1L;
assertNotNull(f.get(objects));
f.set(objects, null);
assertNull(f.get(objects));
}
@Test(expected = IllegalArgumentException.class)
public void testLongObjectNullGet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("L");
assertNull(f.get(objects));
assertEquals(0, f.getLong(objects));
}
/////////////////////////////////////////////////
////////////////////Floats///////////////////////
/////////////////////////////////////////////////
@Test
public void testFloatPrimitiveLegalUse() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("f");
assertEquals(0f, f.getFloat(primitives));
assertEquals(0f, ((Float) f.get(primitives)).floatValue());
f.set(primitives, (float) 1);
assertEquals(1f, f.getFloat(primitives));
assertEquals(1f, ((Float) f.get(primitives)).floatValue());
f.set(primitives, 'a');
f.set(primitives, (byte) 1);
f.set(primitives, (int) 1);
f.set(primitives, (float) 1);
}
@Test
public void testFloatPrimitiveLegalGet() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("f");
assertEquals(0f, f.getFloat(primitives));
assertEquals(0., f.getDouble(primitives));
}
@Test(expected = IllegalArgumentException.class)
public void testFloatPrimitiveIllegalGet_Byte() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("f");
f.getByte(primitives);
}
@Test(expected = IllegalArgumentException.class)
public void testFloatPrimitiveIllegalGet_Short() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("f");
f.getShort(primitives);
}
@Test(expected = IllegalArgumentException.class)
public void testFloatPrimitiveIllegalGet_Int() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("f");
f.getInt(primitives);
}
@Test(expected = IllegalArgumentException.class)
public void testFloatPrimitiveIllegalGet_Long() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("f");
f.getLong(primitives);
}
@Test(expected = IllegalArgumentException.class)
public void testFloatPrimitiveIllegalSet_Boolean() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("f");
f.set(primitives, true);
}
@Test(expected = IllegalArgumentException.class)
public void testFloatPrimitiveIllegalSet_Null() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("f");
f.set(primitives, null);
}
@Test(expected = IllegalArgumentException.class)
public void testFloatObjectIllegalSet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("F");
f.set(objects, (long) 1);
}
@Test
public void testFloatObjectNullSet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("F");
assertNull(f.get(objects));
objects.F = 1f;
assertNotNull(f.get(objects));
f.set(objects, null);
assertNull(f.get(objects));
}
@Test(expected = IllegalArgumentException.class)
public void testFloatObjectNullGet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("F");
assertNull(f.get(objects));
assertEquals(0f, f.getFloat(objects));
}
/////////////////////////////////////////////////
///////////////////Doubles///////////////////////
/////////////////////////////////////////////////
@Test
public void testDoublePrimitiveLegalUse() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("d");
assertEquals(0., f.getDouble(primitives));
assertEquals(0., ((Double) f.get(primitives)).doubleValue());
f.set(primitives, (double) 1);
assertEquals(1., f.getDouble(primitives));
assertEquals(1., ((Double) f.get(primitives)).doubleValue());
f.set(primitives, 'a');
f.set(primitives, (byte) 1);
f.set(primitives, (int) 1);
f.set(primitives, (long) 1);
f.set(primitives, (float) 1);
}
@Test(expected = IllegalArgumentException.class)
public void testDoublePrimitiveIllegalGet_Byte() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("d");
f.getByte(primitives);
}
@Test(expected = IllegalArgumentException.class)
public void testDoublePrimitiveIllegalGet_Short() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("d");
f.getShort(primitives);
}
@Test(expected = IllegalArgumentException.class)
public void testDoublePrimitiveIllegalGet_Int() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("d");
f.getInt(primitives);
}
@Test(expected = IllegalArgumentException.class)
public void testDoublePrimitiveIllegalGet_Long() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("d");
f.getLong(primitives);
}
@Test(expected = IllegalArgumentException.class)
public void testDoublePrimitiveIllegalGet_Float() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("d");
f.getFloat(primitives);
}
@Test(expected = IllegalArgumentException.class)
public void testDoublePrimitiveIllegalSet_Boolean() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("d");
f.set(primitives, true);
}
@Test(expected = IllegalArgumentException.class)
public void testDoublePrimitiveIllegalSet_Null() throws Exception {
assertNotNull(primitives);
Field f = PRIMITIVE_CLASS.getField("d");
f.set(primitives, null);
}
@Test(expected = IllegalArgumentException.class)
public void testDoubleObjectIllegalSet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("D");
f.set(objects, (float) 1);
}
@Test
public void testDoubleObjectNullSet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("D");
assertNull(f.get(objects));
objects.D = 1.;
assertNotNull(f.get(objects));
f.set(objects, null);
assertNull(f.get(objects));
}
@Test(expected = IllegalArgumentException.class)
public void testDoubleObjectNullGet() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("D");
assertNull(f.get(objects));
assertEquals(0., f.getDouble(objects));
}
@Test(expected=IllegalAccessException.class)
public void testSetFinal() throws Exception {
assertNotNull(objects);
Field f = OBJECTS_CLASS.getField("FINAL");
f.set(objects, objects);
}
@Test
public void testDirectInjection_Declared() throws Exception{
ReflectionCaseNoMagic superClass = new ReflectionCaseNoMagic();
Field field = NO_MAGIC.getDeclaredField(PRIVATE_MEMBER);
field.setAccessible(true);
assertFalse(field.getBoolean(superClass));
field.setBoolean(superClass, true);
assertTrue(field.getBoolean(superClass));
}
@Test
public void testDirectInjection_Public() throws Exception{
Field field = NO_MAGIC.getField(PUBLIC_MEMBER);
field.setAccessible(true);
assertFieldFalseToTrue(field, new ReflectionCaseNoMagic());
}
//
// @Test(expected=NoSuchFieldException.class)
// public void testDirectInjection_PublicFail() throws Exception{
// Field field = NO_MAGIC.getField(PRIVATE_MEMBER);
// field.setAccessible(true);
// assertFieldFalseToTrue(field, new ReflectionCaseNoMagic());
// }
//
// @Test(expected=NoSuchFieldException.class)
// public void testDirectInjection_DeclaredFail() throws Exception{
// Field field = NO_MAGIC_SUBCLASS.getDeclaredField(PRIVATE_MEMBER);
// field.setAccessible(true);
// assertFieldFalseToTrue(field, new ReflectionCaseNoMagic.Subclass());
// }
@Test
public void testDirectInjection_Visibility() throws Exception{
ReflectionCaseNoMagic superCase = new ReflectionCaseNoMagic();
ReflectionCaseNoMagic.Subclass subCase = new ReflectionCaseNoMagic.Subclass();
Field superField = NO_MAGIC.getField(OVERRIDE_FIELD);
Field publicField = NO_MAGIC_SUBCLASS.getField(OVERRIDE_FIELD);
Field declaredField = NO_MAGIC_SUBCLASS.getDeclaredField(OVERRIDE_FIELD);
declaredField.setAccessible(true);
assertFalse(declaredField.getBoolean(subCase));
assertFalse(publicField.getBoolean(superCase));
assertFalse(publicField.getBoolean(subCase));
assertFalse(superField.getBoolean(subCase));
assertFalse(superField.getBoolean(superCase));
publicField.setBoolean(superCase, true);
superField.setBoolean(subCase, true);
assertTrue(superCase.overrideField);
assertTrue(superCase.overrideField());
assertTrue(subCase.overrideField());
assertFalse(Subclass.getOverrideField(subCase));
assertTrue(publicField.getBoolean(superCase));
assertTrue(publicField.getBoolean(subCase));
assertTrue(superField.getBoolean(superCase));
assertTrue(superField.getBoolean(subCase));
assertFalse(declaredField.getBoolean(subCase));
}
private void assertFieldFalseToTrue(Field f, Object o) throws Exception {
assertFalse(f.getBoolean(o));
f.setBoolean(o, true);
assertTrue(f.getBoolean(o));
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/junit/AnnotationTests.java | client/src/main/java/collide/junit/AnnotationTests.java | package collide.junit;
import collide.junit.cases.AbstractAnnotation;
import collide.junit.cases.CompileRetention;
import collide.junit.cases.ComplexAnnotation;
import collide.junit.cases.ReflectionCaseHasAllAnnos;
import collide.junit.cases.ReflectionCaseSimple;
import collide.junit.cases.RuntimeRetention;
import collide.junit.cases.SimpleAnnotation;
import org.junit.Test;
import static collide.junit.cases.AbstractAnnotation.MemberType.*;
import static collide.junit.cases.AbstractAnnotation.MemberType.Boolean;
import static collide.junit.cases.AbstractAnnotation.MemberType.Class;
import static collide.junit.cases.AbstractAnnotation.MemberType.Enum;
import static collide.junit.cases.AbstractAnnotation.MemberType.Long;
import static collide.junit.cases.AbstractAnnotation.MemberType.String;
import static xapi.reflect.X_Reflect.magicClass;
import com.google.gwt.core.client.UnsafeNativeLong;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.reflect.client.strategy.ReflectionStrategy;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
@ComplexAnnotation
@SuppressWarnings("all")
@ReflectionStrategy(annotationRetention=ReflectionStrategy.COMPILE|ReflectionStrategy.RUNTIME)
public class AnnotationTests extends AbstractReflectionTest{
static class ValueImpl extends AbstractAnnotation implements SimpleAnnotation {
public ValueImpl() {
this("1");
}
public ValueImpl(String value) {
setValue("value", value);
}
@Override
public Class<? extends Annotation> annotationType() {
return SimpleAnnotation.class;
}
@Override
public String value() {
return getValue("value");
}
@Override
protected String[] members() {
return new String[] {"value"};
}
@Override
protected MemberType[] memberTypes() {
return new MemberType[] {String};
}
}
static class TestCaseImpl extends AbstractAnnotation implements ComplexAnnotation {
private static final String[] members = new String[] {
"singleBool",
"singleInt",
"singleLong",
"singleString",
"singleEnum",
"singleAnnotation",
"singleClass",
"multiBool",
"multiInt",
"multiLong",
"multiString",
"multiEnum",
"multiAnnotation",
"multiClass"
};
private static final MemberType[] types = new MemberType[] {
Boolean,
Int,
Long,
String,
Enum,
Annotation,
Class,
Boolean_Array,
Int_Array,
Long_Array,
String_Array,
Enum_Array,
Annotation_Array,
Class_Array
};
public TestCaseImpl() {
set(
true,
1,
2,
"3",
ElementType.ANNOTATION_TYPE,
new ValueImpl(),
ElementType.class,
new boolean[]{true, false, true},
new int[] {1, 3, 2},
new long[] {2, 4, 3},
new String[] {"3", "0", "a"},
new ElementType[] {ElementType.CONSTRUCTOR, ElementType.ANNOTATION_TYPE},
new SimpleAnnotation[] {new ValueImpl(), new ValueImpl("2")},
new Class<?>[] {ElementType.class, SimpleAnnotation.class}
);
}
@UnsafeNativeLong
public native void set(
boolean singleBool,
int singleInt,
long singleLong,
String singleString,
Enum<?> singleEnum,
Annotation singleAnnotation,
Class<?> singleClass,
boolean[] multiBool,
int[] multiInt,
long[] multiLong,
String[] multiString,
Enum<?>[] multiEnum,
Annotation[] multiAnnotation,
Class<?>[] multiClass
)
/*-{
var m = this.@collide.junit.cases.AbstractAnnotation::memberMap;
m['singleBool'] = singleBool;
m['singleInt'] = singleInt;
m['singleLong'] = singleLong;
m['singleString'] = singleString;
m['singleEnum'] = singleEnum;
m['singleAnnotation'] = singleAnnotation;
m['singleClass'] = singleClass;
m['multiBool'] = multiBool;
m['multiInt'] = multiInt;
m['multiLong'] = multiLong;
m['multiString'] = multiString;
m['multiEnum'] = multiEnum;
m['multiAnnotation'] = multiAnnotation;
m['multiClass'] = multiClass;
}-*/;
@Override
public native boolean singleBool()
/*-{
return this.@collide.junit.cases.AbstractAnnotation::memberMap['singleBool'];
}-*/;
@Override
public native int singleInt()
/*-{
return this.@collide.junit.cases.AbstractAnnotation::memberMap['singleInt'];
}-*/;
@Override
@UnsafeNativeLong
public native long singleLong()
/*-{
return this.@collide.junit.cases.AbstractAnnotation::memberMap['singleLong'];
}-*/;
@Override
public native String singleString()
/*-{
return this.@collide.junit.cases.AbstractAnnotation::memberMap['singleString'];
}-*/;
@Override
public native ElementType singleEnum()
/*-{
return this.@collide.junit.cases.AbstractAnnotation::memberMap['singleEnum'];
}-*/;
@Override
public native SimpleAnnotation singleAnnotation()
/*-{
return this.@collide.junit.cases.AbstractAnnotation::memberMap['singleAnnotation'];
}-*/;
@Override
public native Class<?> singleClass()
/*-{
return this.@collide.junit.cases.AbstractAnnotation::memberMap['singleClass'];
}-*/;
@Override
public native boolean[] multiBool()
/*-{
return this.@collide.junit.cases.AbstractAnnotation::memberMap['multiBool'];
}-*/;
@Override
public native int[] multiInt()
/*-{
return this.@collide.junit.cases.AbstractAnnotation::memberMap['multiInt'];
}-*/;
@Override
@UnsafeNativeLong
public native long[] multiLong()
/*-{
return this.@collide.junit.cases.AbstractAnnotation::memberMap['multiLong'];
}-*/;
@Override
public native String[] multiString()
/*-{
return this.@collide.junit.cases.AbstractAnnotation::memberMap['multiString'];
}-*/;
@Override
public native ElementType[] multiEnum()
/*-{
return this.@collide.junit.cases.AbstractAnnotation::memberMap['multiEnum'];
}-*/;
@Override
public native SimpleAnnotation[] multiAnnotation()
/*-{
return this.@collide.junit.cases.AbstractAnnotation::memberMap['multiAnnotation'];
}-*/;
@Override
public native Class<?>[] multiClass()
/*-{
return this.@collide.junit.cases.AbstractAnnotation::memberMap['multiClass'];
}-*/;
@Override
public Class<? extends Annotation> annotationType() {
return ComplexAnnotation.class;
}
@Override
protected String[] members() {
return members;
}
@Override
protected MemberType[] memberTypes() {
return types;
}
}
@Test
public void testAnnotationMethods() {
if (!GWT.isClient())
return;// Don't let jvms try to load jsni; this @Test is gwt only
TestCaseImpl impl1 = new TestCaseImpl();
TestCaseImpl impl2 = new TestCaseImpl();
assertEquals(impl1, impl2);
assertEquals(impl1.toString(), impl2.toString());
assertEquals(impl1.hashCode(), impl2.hashCode());
}
@Test
public void testSimpleReflection() throws Exception {
final Class<ReflectionCaseSimple> c = ReflectionCaseSimple.class;
ReflectionCaseSimple inst = testNewInstance(magicClass(c));
ReflectionCaseSimple anon = new ReflectionCaseSimple() {};
testAssignable(inst, anon);
testHasNoArgDeclaredMethods(c, "privatePrimitive", "privateObject", "publicPrimitive", "publicObject");
testHasNoArgPublicMethods(c, "publicPrimitive", "publicObject", "hashCode", "toString");
testCantAccessNonPublicMethods(c, "privatePrimitive", "privateObject");
testCantAccessNonDeclaredMethods(c, "hashCode", "toString");
}
@Test
public void testAnnotationsKeepAll() throws Exception {
Class<?> testCase = magicClass(ReflectionCaseHasAllAnnos.class);
Field field = testCase.getDeclaredField("field");
Method method = testCase.getDeclaredMethod("method", Long.class);
Constructor<?> ctor = testCase.getDeclaredConstructor(long.class);
Annotation[] annos = testCase.getAnnotations();
assertHasAnno(testCase, annos, RuntimeRetention.class);
if (GWT.isScript()) {
// Gwt Dev can only access runtime level retention annotations
assertHasAnno(testCase, annos, CompileRetention.class);
}
annos = field.getAnnotations();
assertHasAnno(testCase, annos, RuntimeRetention.class);
if (GWT.isScript()) {
// Gwt Dev can only access runtime level retention annotations
assertHasAnno(testCase, annos, CompileRetention.class);
}
annos = method.getAnnotations();
assertHasAnno(testCase, annos, RuntimeRetention.class);
if (GWT.isScript()) {
// Gwt Dev can only access runtime level retention annotations
assertHasAnno(testCase, annos, CompileRetention.class);
}
annos = ctor.getAnnotations();
assertHasAnno(testCase, annos, RuntimeRetention.class);
if (GWT.isScript()) {
// Gwt Dev can only access runtime level retention annotations
assertHasAnno(testCase, annos, CompileRetention.class);
}
}
private void assertHasAnno(Class<?> cls, Annotation[] annos, Class<? extends Annotation> annoClass) {
for (Annotation anno : annos) {
if (anno.annotationType() == annoClass)
return;
}
fail(cls.getName()+" did not have required annotation "+annoClass);
}
private void testCantAccessNonPublicMethods(Class<?> c, String ... methods) {
for (String method : methods) {
try {
c.getMethod(method);
fail("Could erroneously access non-public method "+method+" in "+c.getName());
} catch (NoSuchMethodException e) {}
}
}
private void testCantAccessNonDeclaredMethods(Class<?> c, String ... methods) {
for (String method : methods) {
try {
c.getDeclaredMethod(method);
fail("Could erroneously access non-declared method "+method+" in "+c.getName());
} catch (NoSuchMethodException e) {}
}
}
private void testHasNoArgDeclaredMethods(Class<?> c, String ... methods) throws Exception{
for (String method : methods) {
assertNotNull(c.getDeclaredMethod(method));
}
}
private void testHasNoArgPublicMethods(Class<?> c, String ... methods) throws Exception{
for (String method : methods) {
assertNotNull(c.getMethod(method));
}
}
private void testAssignable(Object inst, Object anon) {
assertTrue(inst.getClass().isAssignableFrom(anon.getClass()));
assertFalse(anon.getClass().isAssignableFrom(inst.getClass()));
}
private <T> T testNewInstance(Class<T> c) throws Exception {
T newInst = c.newInstance();
assertNotNull(c.getName()+" returned null instead of a new instance", newInst);
assertTrue(c.isAssignableFrom(newInst.getClass()));
return newInst;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/junit/ConstructorTests.java | client/src/main/java/collide/junit/ConstructorTests.java | package collide.junit;
import collide.junit.cases.ReflectionCaseNoMagic;
import org.junit.Test;
import static com.google.gwt.reflect.shared.GwtReflect.magicClass;
import com.google.gwt.reflect.shared.GwtReflect;
import java.lang.reflect.Constructor;
public class ConstructorTests extends AbstractReflectionTest {
public static final Class<? extends SuperCase>
CLS_SUPER_CASE = magicClass(SuperCase.class),
// We purposely want to erase the SubCase to SuperCase,
// to make sure the field type does not influence our lookup.
CLS_SUB_CASE = magicClass(SubCase.class);
@SuppressWarnings("rawtypes")
private static final Class[]
CLS_LONG = new Class[]{long.class},
CLS_STRING = new Class[]{String.class};
protected static class SuperCase {
Object value;
SuperCase() {
value = this;
}
SuperCase(String s) {
value = s;
}
private SuperCase(long j) {
value = j;
}
// Here to make sure sub classes can't find super class public constructors
public SuperCase(Enum<?> e) {
value = e;
}
}
@SuppressWarnings("unused")
protected static class SubCase extends SuperCase {
public SubCase(long l) {
super(l+1);// to differentiate between super and sub class
}
private SubCase(String s) {
super(s+"1");
}
}
@Test
public void testSimpleCtor() throws Throwable {
SuperCase inst;
Constructor<? extends SuperCase> ctor;
ctor = CLS_SUPER_CASE.getDeclaredConstructor(CLS_LONG);
ctor.setAccessible(true);
inst = ctor.newInstance(1);
assertNotNull(inst);
assertEquals((Long)1L, (Long)inst.value);
assertNotEquals(1, inst.value);
ctor = CLS_SUPER_CASE.getDeclaredConstructor(CLS_STRING);
ctor.setAccessible(true);
inst = ctor.newInstance("1");
assertNotNull(inst);
assertEquals("1", inst.value);
}
@Test
public void testSubCaseConstructor() throws Throwable {
SuperCase inst;
Constructor<? extends SuperCase> ctor;
ctor = CLS_SUB_CASE.getConstructor(CLS_LONG);
inst = ctor.newInstance(1);
assertNotNull(inst);
assertEquals(2L, inst.value);// sub class adds 1 to values
ctor = CLS_SUB_CASE.getDeclaredConstructor(CLS_STRING);
ctor.setAccessible(true);
inst = ctor.newInstance("1");
assertNotNull(inst);
assertEquals("11", inst.value);
}
@Test
public void testMagicSuperCase() throws Throwable {
SuperCase inst;
inst = GwtReflect.construct(CLS_SUPER_CASE, CLS_LONG, 1L);
assertNotNull(inst);
assertEquals(1L, inst.value);
inst = GwtReflect.construct(CLS_SUPER_CASE, CLS_STRING, "1");
assertNotNull(inst);
assertEquals("1", inst.value);
}
@Test
public void testDirectInjection_SubCase() throws Throwable {
ReflectionCaseNoMagic inst;
Constructor<? extends ReflectionCaseNoMagic> ctor;
ctor = NO_MAGIC_SUBCLASS.getConstructor(CLS_LONG);
inst = ctor.newInstance(1);
assertNotNull(inst);
assertEquals(2L, inst._long);// sub class adds 1 to values
ctor = NO_MAGIC_SUBCLASS.getDeclaredConstructor(CLS_STRING);
ctor.setAccessible(true);
inst = ctor.newInstance("1");
assertNotNull(inst);
assertEquals("11", inst._String);
}
@Test
public void testDirectConstruction_SubCase() throws Throwable {
SuperCase inst;
inst = GwtReflect.construct(CLS_SUB_CASE, CLS_LONG, 1L);
assertNotNull(inst);
assertEquals(2L, inst.value);
inst = GwtReflect.construct(CLS_SUB_CASE, CLS_STRING, "1");
assertNotNull(inst);
assertEquals("11", inst.value);
}
@Test
public void testConstructorVisibility() throws Throwable {
Constructor<?>[] ctors = SubCase.class.getConstructors();
assertEquals(1, ctors.length); // Must not return super class constructors!!
SubCase inst = (SubCase) ctors[0].newInstance(1);
assertEquals(2L, inst.value);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/junit/ComparisonFailure.java | client/src/main/java/collide/junit/ComparisonFailure.java | package collide.junit;
/**
* Thrown when an {@link org.junit.Assert#assertEquals(Object, Object) assertEquals(String, String)} fails. Create and throw
* a <code>ComparisonFailure</code> manually if you want to show users the difference between two complex
* strings.
*
* Inspired by a patch from Alex Chaffee (alex@purpletech.com)
*
* @since 4.0
*/
public class ComparisonFailure extends AssertionError {
/**
* The maximum length for fExpected and fActual. If it is exceeded, the strings should be shortened.
*
* @see ComparisonCompactor
*/
private static final int MAX_CONTEXT_LENGTH = 20;
private static final long serialVersionUID = 1L;
private String fExpected;
private String fActual;
/**
* Constructs a comparison failure.
*
* @param message the identifying message or null
* @param expected the expected string value
* @param actual the actual string value
*/
public ComparisonFailure(String message, String expected, String actual) {
super(message);
fExpected = expected;
fActual = actual;
}
/**
* Returns "..." in place of common prefix and "..." in
* place of common suffix between expected and actual.
*
* @see Throwable#getMessage()
*/
@Override
public String getMessage() {
return new ComparisonCompactor(MAX_CONTEXT_LENGTH, fExpected, fActual).compact(super.getMessage());
}
/**
* Returns the actual string value
*
* @return the actual string value
*/
public String getActual() {
return fActual;
}
/**
* Returns the expected string value
*
* @return the expected string value
*/
public String getExpected() {
return fExpected;
}
private static class ComparisonCompactor {
private static final String ELLIPSIS = "...";
private static final String DELTA_END = "]";
private static final String DELTA_START = "[";
/**
* The maximum length for <code>expected</code> and <code>actual</code>. When <code>contextLength</code>
* is exceeded, the Strings are shortened
*/
private int fContextLength;
private String fExpected;
private String fActual;
private int fPrefix;
private int fSuffix;
/**
* @param contextLength the maximum length for <code>expected</code> and <code>actual</code>. When contextLength
* is exceeded, the Strings are shortened
* @param expected the expected string value
* @param actual the actual string value
*/
public ComparisonCompactor(int contextLength, String expected, String actual) {
fContextLength = contextLength;
fExpected = expected;
fActual = actual;
}
private String compact(String message) {
if (fExpected == null || fActual == null || areStringsEqual()) {
return AbstractReflectionTest.format(message, fExpected, fActual);
}
findCommonPrefix();
findCommonSuffix();
String expected = compactString(fExpected);
String actual = compactString(fActual);
return AbstractReflectionTest.format(message, expected, actual);
}
private String compactString(String source) {
String result = DELTA_START + source.substring(fPrefix, source.length() - fSuffix + 1) + DELTA_END;
if (fPrefix > 0) {
result = computeCommonPrefix() + result;
}
if (fSuffix > 0) {
result = result + computeCommonSuffix();
}
return result;
}
private void findCommonPrefix() {
fPrefix = 0;
int end = Math.min(fExpected.length(), fActual.length());
for (; fPrefix < end; fPrefix++) {
if (fExpected.charAt(fPrefix) != fActual.charAt(fPrefix)) {
break;
}
}
}
private void findCommonSuffix() {
int expectedSuffix = fExpected.length() - 1;
int actualSuffix = fActual.length() - 1;
for (; actualSuffix >= fPrefix && expectedSuffix >= fPrefix; actualSuffix--, expectedSuffix--) {
if (fExpected.charAt(expectedSuffix) != fActual.charAt(actualSuffix)) {
break;
}
}
fSuffix = fExpected.length() - expectedSuffix;
}
private String computeCommonPrefix() {
return (fPrefix > fContextLength ? ELLIPSIS : "") + fExpected.substring(Math.max(0, fPrefix - fContextLength), fPrefix);
}
private String computeCommonSuffix() {
int end = Math.min(fExpected.length() - fSuffix + 1 + fContextLength, fExpected.length());
return fExpected.substring(fExpected.length() - fSuffix + 1, end) + (fExpected.length() - fSuffix + 1 < fExpected.length() - fContextLength ? ELLIPSIS : "");
}
private boolean areStringsEqual() {
return fExpected.equals(fActual);
}
}
} | java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/junit/cases/AbstractAnnotation.java | client/src/main/java/collide/junit/cases/AbstractAnnotation.java | package collide.junit.cases;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.reflect.shared.GwtReflect;
import java.lang.annotation.Annotation;
import java.util.Arrays;
/**
* A somewhat ugly, but functional implementation of an annotation;
* it should never be used in production, but it exposes a relatively simple
* and correct api for "how an annotation should behave".
* <p>
*
* @author "james@wetheinter.net"
*
*/
public abstract class AbstractAnnotation extends SourceVisitor{
public static enum MemberType {
Boolean, Byte, Short, Int, Long, Float, Double, Class, Enum, String, Annotation,
Boolean_Array, Byte_Array, Short_Array, Int_Array, Long_Array, Float_Array,
Double_Array, Class_Array, Enum_Array, String_Array, Annotation_Array
}
private final JavaScriptObject memberMap;
public AbstractAnnotation() {
this(JavaScriptObject.createObject());
}
public AbstractAnnotation(JavaScriptObject memberMap) {
this.memberMap = memberMap;
}
public abstract Class<? extends Annotation> annotationType();
protected abstract String[] members();
protected abstract MemberType[] memberTypes();
protected final native <T> T getValue(String member)
/*-{
return this.@collide.junit.cases.AbstractAnnotation::memberMap[member];
}-*/;
protected final native void setValue(String member, Object value)
/*-{
this.@collide.junit.cases.AbstractAnnotation::memberMap[member] = value;
}-*/;
@Override
public final int hashCode() {
String[] members = members();
MemberType[] types = memberTypes();
int hash = 0, i = members.length;
for (; i-- > 0;) {
String member = members[i];
switch (types[i]) {
case Annotation:
case Class:
case Enum:
case String:
hash += ((127) * member.hashCode()) ^ getObjectHash(member);
break;
case Boolean:
hash += ((127) * member.hashCode()) ^ getBoolInt(member);
break;
case Byte:
case Int:
case Short:
case Float:
case Double:
hash += ((127) * member.hashCode()) ^ getInt(member);
break;
case Long:
hash += ((127) * member.hashCode()) ^ (int)getLong(memberMap, member);
break;
case Annotation_Array:
case Class_Array:
case Enum_Array:
case String_Array:
hash += ((127) * member.hashCode()) ^ Arrays.hashCode(this.<Object[]>getValue(member));
break;
case Boolean_Array:
case Byte_Array:
case Int_Array:
case Short_Array:
case Float_Array:
case Double_Array:
hash += ((127) * member.hashCode()) ^ getPrimitiveArrayHash(member);
break;
case Long_Array:
hash += ((127) * member.hashCode()) ^ Arrays.hashCode(this.<long[]>getValue(member));
}
}
return hash;
}
@Override
public String toString() {
StringBuilder b = new StringBuilder("@");
b.append(annotationType().getName());
b.append(" (");
String[] members = members();
if (members.length == 0) {
b.append(")");
return b.toString();
}
MemberType[] types = memberTypes();
b.append(members[0]);
b.append(" = ");
b.append(toString(members[0], types[0]));
for (int i = 1, m = members.length; i < m; i++) {
b.append(", ");
b.append(members[i]);
b.append(" = ");
b.append(toString(members[i], types[i]));
}
b.append(")");
return b.toString();
}
/**
* From java.lang.annotation:
* Returns true if the specified object represents an annotation that is
* logically equivalent to this one. In other words, returns true if the specified object is an instance of
* the same annotation type as this instance, all of whose members are equal to the corresponding member of
* this annotation, as defined below:
* <ul>
* <li>Two corresponding primitive typed members whose values are <tt>x</tt> and <tt>y</tt> are considered
* equal if <tt>x == y</tt>, unless their type is <tt>float</tt> or <tt>double</tt>.
* <li>Two corresponding <tt>float</tt> members whose values are <tt>x</tt> and <tt>y</tt> are considered
* equal if <tt>Float.valueOf(x).equals(Float.valueOf(y))</tt>. (Unlike the <tt>==</tt> operator, NaN is
* considered equal to itself, and <tt>0.0f</tt> unequal to <tt>-0.0f</tt>.)
* <li>Two corresponding <tt>double</tt> members whose values are <tt>x</tt> and <tt>y</tt> are considered
* equal if <tt>Double.valueOf(x).equals(Double.valueOf(y))</tt>. (Unlike the <tt>==</tt> operator, NaN is
* considered equal to itself, and <tt>0.0</tt> unequal to <tt>-0.0</tt>.)
* <li>Two corresponding <tt>String</tt>, <tt>Class</tt>, enum, or annotation typed members whose values are
* <tt>x</tt> and <tt>y</tt> are considered equal if <tt>x.equals(y)</tt>. (Note that this definition is
* recursive for annotation typed members.)
* <li>Two corresponding array typed members <tt>x</tt> and <tt>y</tt> are considered equal if
* <tt>Arrays.equals(x, y)</tt>, for the appropriate overloading of {@link java.util.Arrays#equals}.
* </ul>
*
* @return true if the specified object represents an annotation that is logically equivalent to this one,
* otherwise false
*/
@Override
public final boolean equals(Object o) {
if (o == this) return true;
if (o instanceof AbstractAnnotation) {
AbstractAnnotation you = (AbstractAnnotation)o;
MemberType[] myTypes = memberTypes();
if (!Arrays.equals(myTypes, you.memberTypes())) return false;
String[] myMembers = members();
String[] yourMembers = you.members();
// These member lists are generated, so they will always be in the same order for the same type
if (myMembers.length == yourMembers.length) {
for (int i = myMembers.length; i-- > 0;) {
String key = myMembers[i];
if (!key.equals(yourMembers[i])) return false;
MemberType type = myTypes[i];
assert !isNull(key);
assert !you.isNull(key);
switch (type) {
case Annotation:
if (getValue(key).equals(you.getValue(key))) continue;
return false;
case Class:
case Enum:
case String:
case Boolean:
case Byte:
case Int:
case Short:
case Float:
case Double:
if (quickEquals(key, you.memberMap))
continue;
return false;
case Long:
if (getLong(memberMap, key) == getLong(you.memberMap, key))
continue;
return false;
case Annotation_Array:
case Class_Array:
case Enum_Array:
case String_Array:
if (arraysEqualObject(getValue(key), you.getValue(key)))
continue;
return false;
case Boolean_Array:
case Byte_Array:
case Int_Array:
case Short_Array:
case Float_Array:
case Double_Array:
if (arraysEqualPrimitive(getValue(key), you.getValue(key)))
continue;
return false;
case Long_Array:
if (arraysEqualLong(getValue(key), you.getValue(key)))
continue;
return false;
}
}// end for loop
return true;
}
}
return false;
}
private String toString(String key, MemberType memberType) {
switch (memberType) {
case Class:
Class<?> c = getValue(key);
return c.getName() + ".class";
case Enum:
Enum<?> e = getValue(key);
return e.getDeclaringClass().getName() + "." + e.name();
case Boolean:
case Byte:
case Int:
case Short:
case Float:
case Double:
return getNativeString(key);
case Long:
return String.valueOf(getLong(memberMap, key));
case Class_Array:
StringBuilder b = new StringBuilder("{ ");
Class<?>[] classes = this.<Class<?>[]>getValue(key);
if (classes.length > 0) {
b.append(classes[0].getName()).append(".class");
for (int i = 1, m = classes.length; i < m; i++) {
b.append(", ").append(classes[i].getName()).append(".class");
}
}
b.append(" }");
return b.toString();
case Enum_Array:
b = new StringBuilder("{ ");
Enum<?>[] enums = this.<Enum<?>[]>getValue(key);
if (enums.length > 0) {
b.append(enums[0].getDeclaringClass().getName()).append(".").append(enums[0].name());
for (int i = 1, m = enums.length; i < m; i++) {
b.append(", ").append(enums[i].getDeclaringClass().getName()).append(".").append(enums[i].name());
}
}
b.append(" }");
return b.toString();
case String_Array:
b = new StringBuilder("{ ");
String[] strings = this.<String[]>getValue(key);
if (strings.length > 0) {
b.append('"').append(strings[0]).append('"');
for (int i = 1, m = strings.length; i < m; i++) {
b.append(", \"").append(strings[i]).append('"');
}
}
b.append(" }");
return b.toString();
case Long_Array:
b = new StringBuilder("{ ");
long[] longs = this.<long[]>getValue(key);
if (longs.length > 0) {
b.append(longs[0]);
if (longs[0] > Integer.MAX_VALUE)
b.append('L');
for (int i = 1, m = longs.length; i < m; i++) {
b.append(", ").append(longs[i]);
if (longs[i] > Integer.MAX_VALUE)
b.append('L');
}
}
b.append(" }");
return b.toString();
case Annotation_Array:
case Boolean_Array:
case Byte_Array:
case Int_Array:
case Short_Array:
case Float_Array:
case Double_Array:
b = new StringBuilder("{ ");
arrayToString(b, key);
b.append(" }");
return b.toString();
case String:
return "\"" + GwtReflect.escape(this.<String>getValue(key)) + "\"";
case Annotation:
default:
return String.valueOf(getValue(key));
}
}
private native void arrayToString(StringBuilder b, String key)
/*-{
var i = 0, o = this.@collide.junit.cases.AbstractAnnotation::memberMap[key], m = o.length;
if (m > 0) {
b.@java.lang.StringBuilder::append(Ljava/lang/String;)(""+o[i++]);
for (;i < m; i++) {
b.@java.lang.StringBuilder::append(Ljava/lang/String;)(", ");
b.@java.lang.StringBuilder::append(Ljava/lang/String;)(""+o[i]);
}
}
}-*/;
private final native String getNativeString(String key)
/*-{
return ''+this.@collide.junit.cases.AbstractAnnotation::memberMap[key];
}-*/;
private native int getPrimitiveArrayHash(String member)
/*-{
var hash = 1;
var arr = this.@collide.junit.cases.AbstractAnnotation::memberMap[member];
for ( var i in arr) {
hash += 31*(~~arr[i]);// GWT's number hash codes just cast to int anyway
}
return hash;
}-*/;
private native int getInt(String member)
/*-{
return this.@collide.junit.cases.AbstractAnnotation::memberMap[member];
}-*/;
private native int getBoolInt(String member)
/*-{
return this.@collide.junit.cases.AbstractAnnotation::memberMap[member] ? 1 : 0;
}-*/;
private final int getObjectHash(String member) {
Object value = getValue(member);
assert value != null : "Annotations can never have null values. No member " + member + " in " + this;
return value.hashCode();
}
private final native boolean isNull(String key)
/*-{
return this.@collide.junit.cases.AbstractAnnotation::memberMap[key] == null;
}-*/;
private final native boolean quickEquals(String key, JavaScriptObject you)
/*-{
return you[key] === this.@collide.junit.cases.AbstractAnnotation::memberMap[key];
}-*/;
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/junit/cases/CompileRetention.java | client/src/main/java/collide/junit/cases/CompileRetention.java | package collide.junit.cases;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.CLASS)
public @interface CompileRetention{} | java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/junit/cases/ReflectionCaseSimple.java | client/src/main/java/collide/junit/cases/ReflectionCaseSimple.java | package collide.junit.cases;
/**
* A simple reflection case;
* a class with no annotations, and one of everything to reflect upon.
*
* @author James X. Nelson (james@wetheinter.net)
*
*/
public class ReflectionCaseSimple {
static @interface Anno{}
public ReflectionCaseSimple() {
this(1, "1", 1, 1.0);
}
@Anno
public ReflectionCaseSimple(int privatePrimitive, String privateObject, long publicPrimitive, Object ... publicObjects) {
this.privatePrimitive = privatePrimitive;
this.privateObject = privateObject;
this.publicPrimitive = publicPrimitive;
this.publicObject = publicObjects;
}
private int privatePrimitive;
private String privateObject;
@Anno
public long publicPrimitive;
public Object[] publicObject;
@Anno
private int privatePrimitive() {
return privatePrimitive;
}
@SuppressWarnings("unused")
private String privateObject() {
return privateObject;
}
public long publicPrimitive() {
return publicPrimitive;
}
public Object[] publicObject() {
return publicObject;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/junit/cases/ReflectionCaseHasAllAnnos.java | client/src/main/java/collide/junit/cases/ReflectionCaseHasAllAnnos.java | package collide.junit.cases;
import static com.google.gwt.reflect.client.strategy.ReflectionStrategy.COMPILE;
import static com.google.gwt.reflect.client.strategy.ReflectionStrategy.RUNTIME;
import com.google.gwt.reflect.client.strategy.GwtRetention;
import com.google.gwt.reflect.client.strategy.ReflectionStrategy;
@SourceRetention
@CompileRetention
@RuntimeRetention
@ReflectionStrategy(
annotationRetention=COMPILE|RUNTIME
,methodRetention=@GwtRetention(annotationRetention=COMPILE|RUNTIME)
,fieldRetention=@GwtRetention(annotationRetention=COMPILE|RUNTIME)
,constructorRetention=@GwtRetention(annotationRetention=COMPILE|RUNTIME)
,typeRetention=@GwtRetention(annotationRetention=COMPILE|RUNTIME)
)
public class ReflectionCaseHasAllAnnos {
protected ReflectionCaseHasAllAnnos() {}
@SourceRetention
@CompileRetention
@RuntimeRetention
public ReflectionCaseHasAllAnnos(
@SourceRetention
@CompileRetention
@RuntimeRetention
long param
) { }
@SourceRetention
@CompileRetention
@RuntimeRetention
private long field;
@SourceRetention
@CompileRetention
@RuntimeRetention
long method(
@SourceRetention
@CompileRetention
@RuntimeRetention
Long param
) { return field; }
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/junit/cases/SimpleAnnotation.java | client/src/main/java/collide/junit/cases/SimpleAnnotation.java | package collide.junit.cases;
public @interface SimpleAnnotation {String value() default "1";} | java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/junit/cases/SourceRetention.java | client/src/main/java/collide/junit/cases/SourceRetention.java | package collide.junit.cases;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.SOURCE)
public @interface SourceRetention{} | java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/junit/cases/SourceVisitor.java | client/src/main/java/collide/junit/cases/SourceVisitor.java | package collide.junit.cases;
import java.util.Arrays;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.UnsafeNativeLong;
public class SourceVisitor {
protected boolean arraysEqualPrimitive(Object v1, Object v2) {
// Fast at runtime; correct at test time.
assert v1 != null : new NullPointerException();
assert v1.getClass().getComponentType().isPrimitive() :
"Non primitive array sent as first arg to arrayEqualPrimitive in "+getClass()+": "+v1;
assert v2 != null : new NullPointerException();
assert v2.getClass().getComponentType().isPrimitive() :
"Non primitive array sent as second arg to arrayEqualPrimitive in "+getClass()+": "+v2;
return nativePrimitivesEqual(v1, v2);
}
protected native boolean nativePrimitivesEqual(Object v1, Object v2)
/*-{
var i = v1.length; // v1 never null
if (v2 == null || v2.length != i) return false;
for (; i-- > 0;) {
if (v1[i] != v2[i]) {// we're only sending non-long primitives here
return false;
}
}
return true;
}-*/;
protected boolean arraysEqualLong(Object zero, Object one) {
assert zero instanceof long[] : "Non-long array as first argument to arraysEqualLong in "+getClass()
+":\n"+zero;
assert one instanceof long[] : "Non-long array as second argument to arraysEqualLong in "+getClass()
+":\n"+one;
return Arrays.equals((long[])zero, (long[])one);
}
protected boolean arraysEqualObject(Object zero, Object one) {
assert zero instanceof Object[] : "Non-Object array as first argument to arraysEqualObject in "+getClass()
+":\n"+zero+" "+zero.getClass();
assert one instanceof Object[] : "Non-Object array as second argument to arraysEqualObject in "+getClass()
+":\n"+one+" "+one.getClass();
return Arrays.equals((Object[])zero, (Object[])one);
}
@UnsafeNativeLong
protected static native long getLong(JavaScriptObject object, String member)
/*-{
return object[member];
}-*/;
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/junit/cases/ReflectionCaseKeepsEverything.java | client/src/main/java/collide/junit/cases/ReflectionCaseKeepsEverything.java | package collide.junit.cases;
import com.google.gwt.reflect.client.strategy.ReflectionStrategy;
@RuntimeRetention
@ReflectionStrategy(keepEverything=true)
public class ReflectionCaseKeepsEverything extends ReflectionCaseSuperclass{
public ReflectionCaseKeepsEverything() {}
@CompileRetention
private class Subclass extends ReflectionCaseKeepsEverything {
@RuntimeRetention
long privateCall;
@CompileRetention
Long publicCall;
@CompileRetention private void privateCall() {
privateCall+=2;
}
@RuntimeRetention public void publicCall() {
publicCall = 2L;
}
}
@RuntimeRetention
long privateCall;
@CompileRetention
Long publicCall;
@CompileRetention private void privateCall() {
privateCall++;
}
@RuntimeRetention public void publicCall() {
publicCall = 1L;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/junit/cases/ReflectionCaseKeepsNothing.java | client/src/main/java/collide/junit/cases/ReflectionCaseKeepsNothing.java | package collide.junit.cases;
import com.google.gwt.reflect.client.strategy.ReflectionStrategy;
@RuntimeRetention
@ReflectionStrategy(keepNothing=true)
public class ReflectionCaseKeepsNothing extends ReflectionCaseSuperclass{
public ReflectionCaseKeepsNothing() {}
@RuntimeRetention
private class Subclass extends ReflectionCaseKeepsNothing {
@RuntimeRetention
long privateCall;
@CompileRetention
Long publicCall;
@CompileRetention private void privateCall() {
privateCall+=2;
}
@RuntimeRetention public void publicCall() {
publicCall = 2L;
}
}
@RuntimeRetention
long privateCall;
@CompileRetention
Long publicCall;
@CompileRetention private void privateCall() {
privateCall++;
}
@RuntimeRetention public void publicCall() {
publicCall = 1L;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/junit/cases/ReflectionCaseNoMagic.java | client/src/main/java/collide/junit/cases/ReflectionCaseNoMagic.java | package collide.junit.cases;
public class ReflectionCaseNoMagic {
public static class Subclass extends ReflectionCaseNoMagic {
protected boolean overrideField;// shadows the superclass field
public static boolean getOverrideField(Subclass s) {
return s.overrideField;
}
public Subclass() {}
protected Subclass(String s) {
super(s+"1");
}
public Subclass(long l) {
super(l+1);
}
}
public ReflectionCaseNoMagic() {}
protected ReflectionCaseNoMagic(String s) {
_String = s;
}
private ReflectionCaseNoMagic(long l) {
this._long = l;
}
@RuntimeRetention
private boolean privateCall;
@RuntimeRetention
public boolean publicCall;
public boolean overrideField;
boolean _boolean;
byte _byte;
short _short;
char _char;
int _int;
public long _long;
float _float;
double _double;
public String _String;
@SuppressWarnings("unused")
private void privateCall() { privateCall = true; }
public void publicCall() { publicCall = true; }
public boolean wasPrivateCalled(){return privateCall;}
public boolean overrideField() {
return this.overrideField;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/junit/cases/RuntimeRetention.java | client/src/main/java/collide/junit/cases/RuntimeRetention.java | package collide.junit.cases;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface RuntimeRetention{} | java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/junit/cases/ReflectionCaseSubclass.java | client/src/main/java/collide/junit/cases/ReflectionCaseSubclass.java | package collide.junit.cases;
@SuppressWarnings("unused")
public class ReflectionCaseSubclass extends ReflectionCaseSuperclass {
// Exact same fields as super class so we can test behavior
private boolean privateCall;
public boolean publicCall;
private void privateCall(long l) {
privateCall = true;
}
public void publicCall(Long l) {
publicCall = true;
}
} | java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/junit/cases/ReflectionCaseSuperclass.java | client/src/main/java/collide/junit/cases/ReflectionCaseSuperclass.java | package collide.junit.cases;
import com.google.gwt.reflect.client.strategy.ReflectionStrategy;
@RuntimeRetention
@SuppressWarnings("unused")
public class ReflectionCaseSuperclass {
@CompileRetention
protected class InnerType {}
private boolean privateCall;
public boolean publicCall;
boolean _boolean;
byte _byte;
short _short;
char _char;
int _int;
long _long;
float _float;
double _double;
private void privateCall() { privateCall = true; }
public void publicCall() { publicCall = true; }
public boolean wasPrivateCalled(){return privateCall;}
boolean _boolean(){return _boolean;}
byte _byte(){return _byte;}
short _short(){return _short;}
char _char(){return _char;}
int _int(){return _int;}
long _long(){return _long;}
float _float(){return _float;}
double _double(){return _double;}
} | java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/junit/cases/ComplexAnnotation.java | client/src/main/java/collide/junit/cases/ComplexAnnotation.java | package collide.junit.cases;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface ComplexAnnotation {
boolean singleBool() default true;
int singleInt() default 1;
long singleLong() default 2;
String singleString() default "3";
ElementType singleEnum() default ElementType.ANNOTATION_TYPE;
SimpleAnnotation singleAnnotation() default @SimpleAnnotation;
Class<?> singleClass() default ElementType.class;
boolean[] multiBool() default {true, false, true};
int[] multiInt() default {1, 3, 2};
long[] multiLong() default {2, 4, 3};
String[] multiString() default {"3", "0", "a"};
ElementType[] multiEnum() default {ElementType.CONSTRUCTOR, ElementType.ANNOTATION_TYPE};
SimpleAnnotation[] multiAnnotation() default {@SimpleAnnotation, @SimpleAnnotation(value="2")};
Class<?>[] multiClass() default {ElementType.class, SimpleAnnotation.class};
} | java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/junit/cases/ReflectionCaseMagicSupertype.java | client/src/main/java/collide/junit/cases/ReflectionCaseMagicSupertype.java | package collide.junit.cases;
import com.google.gwt.reflect.client.strategy.ReflectionStrategy;
@ReflectionStrategy(
keepEverything=true
)
public class ReflectionCaseMagicSupertype {
ReflectionCaseMagicSupertype() {
this(0);
}
public ReflectionCaseMagicSupertype(long field) {
publicField = field;
}
private int privateField;
public final long publicField;
@SuppressWarnings("unused")
private int privateMethod() {
return privateField;
}
public long publicMethod() {
return publicField;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/demo/controller/DemoController.java | client/src/main/java/collide/demo/controller/DemoController.java | package collide.demo.controller;
import collide.client.editor.DefaultEditorConfiguration;
import collide.client.editor.EditorConfiguration;
import collide.client.editor.EditorToolbar;
import collide.client.filetree.AppContextFileTreeController;
import collide.client.filetree.FileTreeController;
import collide.client.filetree.FileTreeModel;
import collide.client.filetree.FileTreeModelNetworkController;
import collide.client.util.Elements;
import collide.demo.view.DemoView;
import collide.plugin.client.launcher.LauncherService;
import collide.plugin.client.standalone.StandaloneCodeBundle;
import com.google.collide.client.AppContext;
import com.google.collide.client.CollideSettings;
import com.google.collide.client.Resources;
import com.google.collide.client.code.NavigationAreaExpansionEvent;
import com.google.collide.client.code.ParticipantModel;
import com.google.collide.client.collaboration.CollaborationManager;
import com.google.collide.client.collaboration.DocOpsSavedNotifier;
import com.google.collide.client.collaboration.IncomingDocOpDemultiplexer;
import com.google.collide.client.communication.FrontendApi.ApiCallback;
import com.google.collide.client.document.DocumentManager;
import com.google.collide.client.document.DocumentManager.LifecycleListener;
import com.google.collide.client.editor.Editor;
import com.google.collide.client.history.Place;
import com.google.collide.client.plugin.ClientPlugin;
import com.google.collide.client.plugin.ClientPluginService;
import com.google.collide.client.plugin.FileAssociation;
import com.google.collide.client.plugin.RunConfiguration;
import com.google.collide.client.search.TreeWalkFileNameSearchImpl;
import com.google.collide.client.ui.button.ImageButton;
import com.google.collide.client.ui.panel.MultiPanel;
import com.google.collide.client.workspace.Header;
import com.google.collide.client.workspace.KeepAliveTimer;
import com.google.collide.client.workspace.UnauthorizedUser;
import com.google.collide.client.workspace.WorkspacePlace;
import com.google.collide.client.workspace.WorkspaceShell;
import com.google.collide.dto.FileContents;
import com.google.collide.dto.GetWorkspaceMetaDataResponse;
import com.google.collide.dto.ServerError.FailureReason;
import com.google.collide.dto.client.DtoClientImpls.GetWorkspaceMetaDataImpl;
import com.google.collide.dto.client.DtoClientImpls.GetWorkspaceMetaDataResponseImpl;
import com.google.collide.json.client.JsoArray;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.plugin.PublicService;
import com.google.collide.shared.plugin.PublicServices;
import com.google.collide.shared.util.ListenerRegistrar.Remover;
import com.google.collide.shared.util.ListenerRegistrar.RemoverManager;
import elemental.client.Browser;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.events.EventRemover;
import elemental.events.KeyboardEvent;
import elemental.events.KeyboardEvent.KeyCode;
import elemental.util.Collections;
import elemental.util.MapFromStringTo;
import xapi.log.X_Log;
import xapi.util.X_String;
import xapi.util.api.RemovalHandler;
import com.google.gwt.resources.client.ImageResource;
public class DemoController
implements ClientPlugin<WorkspacePlace>, LauncherService
{
private AppContext appContext;
private DocumentManager documentManager;
private RemoverManager keyListenerRemoverManager;
private TreeWalkFileNameSearchImpl searchIndex;
private ParticipantModel participantModel;
private CollaborationManager collaborationManager;
private StandaloneCodeBundle codePanelBundle;
protected KeepAliveTimer keepAliveTimer;
private WorkspacePlace workspacePlace;
private DemoView view;
public DemoController(AppContext context) {
this.appContext = context;
this.keyListenerRemoverManager = new RemoverManager();
this.searchIndex = TreeWalkFileNameSearchImpl.create();
PublicServices.registerService(LauncherService.class,
new PublicService.DefaultServiceProvider<LauncherService>(LauncherService.class, this)
);
}
public void initialize(DemoView view, final ClientPluginService plugins) {
this.view = view;
final Resources res = appContext.getResources();
WorkspaceShell.View workspaceShellView = new WorkspaceShell.View(res, false);
workspacePlace = WorkspacePlace.PLACE; // Used to come from event...
workspacePlace.setIsStrict(false);
FileTreeController<?> fileTreeController = new AppContextFileTreeController(appContext);
FileTreeModelNetworkController.OutgoingController fileTreeModelOutgoingNetworkController = new FileTreeModelNetworkController.OutgoingController(
fileTreeController);
FileTreeModel fileTreeModel = new FileTreeModel(fileTreeModelOutgoingNetworkController);
documentManager = DocumentManager.create(fileTreeModel, fileTreeController);
searchIndex.setFileTreeModel(fileTreeModel);
participantModel = ParticipantModel.create(appContext.getFrontendApi(), appContext.getMessageFilter());
IncomingDocOpDemultiplexer docOpRecipient = IncomingDocOpDemultiplexer.create(appContext.getMessageFilter());
collaborationManager = CollaborationManager.create(appContext, documentManager, participantModel,
docOpRecipient);
DocOpsSavedNotifier docOpSavedNotifier = new DocOpsSavedNotifier(documentManager, collaborationManager);
FileTreeModelNetworkController fileNetworkController = FileTreeModelNetworkController.create(fileTreeModel, fileTreeController, workspacePlace);
final Header header = Header.create(workspaceShellView.getHeaderView(), workspaceShellView, workspacePlace,
appContext, searchIndex, fileTreeModel);
final WorkspaceShell shell = WorkspaceShell.create(workspaceShellView, header);
// Add a HotKey listener for to auto-focus the AwesomeBox.
/* The GlobalHotKey stuff utilizes the wave signal event stuff which filters alt+enter as an unimportant
* event. This prevents us from using the GlobalHotKey manager here. Note: This is capturing since the
* editor likes to nom-nom keys, in the dart re-write lets think about this sort of stuff ahead of time. */
final EventRemover eventRemover = Elements.getBody().addEventListener(Event.KEYDOWN, new EventListener() {
@Override
public void handleEvent(Event evt) {
KeyboardEvent event = (KeyboardEvent)evt;
if (event.isAltKey() && event.getKeyCode() == KeyCode.ENTER) {
appContext.getAwesomeBoxComponentHostModel().revertToDefaultComponent();
header.getAwesomeBoxComponentHost().show();
}
}
}, true);
// Track this for removal in cleanup
keyListenerRemoverManager.track(eventRemover::remove);
codePanelBundle = new StandaloneCodeBundle(appContext, shell, fileTreeController, fileTreeModel, searchIndex,
documentManager, participantModel, docOpRecipient, workspacePlace){
@Override
protected ClientPluginService initPlugins(MultiPanel<?, ?> masterPanel) {
return plugins;
}
};
codePanelBundle.attach(true, new DefaultEditorConfiguration());
codePanelBundle.setMasterPanel(view);
// Attach to the DOM.
view.append(shell);
view.append(header);
workspacePlace.fireEvent(new NavigationAreaExpansionEvent(false));
documentManager.getLifecycleListenerRegistrar().add(new LifecycleListener() {
@Override
public void onDocumentUnlinkingFromFile(Document document) {
X_Log.info("unlinked from file",document);
}
@Override
public void onDocumentOpened(Document document, Editor editor) {
X_Log.info("opened",document);
}
@Override
public void onDocumentLinkedToFile(Document document,
FileContents fileContents) {
X_Log.info("linked to file",document);
}
@Override
public void onDocumentGarbageCollected(Document document) {
X_Log.info("gc'd",document);
}
@Override
public void onDocumentCreated(Document document) {
X_Log.info("created",document);
}
@Override
public void onDocumentClosed(Document document, Editor editor) {
X_Log.info("closed",document);
}
});
final GetWorkspaceMetaDataResponseImpl localRequest = GetWorkspaceMetaDataResponseImpl.make();
final ApiCallback<GetWorkspaceMetaDataResponse> callback = new ApiCallback<GetWorkspaceMetaDataResponse>() {
boolean once = true;
@Override
public void onMessageReceived(GetWorkspaceMetaDataResponse message) {
if (!workspacePlace.isActive() && localRequest.getWorkspaceName() == null) {
return;
}
if (once) {
once = false;
// Start the keep-alive timer at 5 second intervals.
keepAliveTimer = new KeepAliveTimer(appContext, 5000);
keepAliveTimer.start();
codePanelBundle.enterWorkspace(true, workspacePlace, message);
}
}
@Override
public void onFail(FailureReason reason) {
if (FailureReason.UNAUTHORIZED == reason) {
/* User is not authorized to access this workspace. At this point, the components of the
* WorkspacePlace already sent multiple requests to the frontend that are bound to fail with the
* same reason. However, we don't want to gate loading the workspace to handle the rare case that
* a user accesses a branch that they do not have permission to access. Better to make the
* workspace load fast and log errors if the user is not authorized. */
UnauthorizedUser unauthorizedUser = UnauthorizedUser.create(res);
shell.setPerspective(unauthorizedUser.getView().getElement());
}
}
};
CollideSettings settings = CollideSettings.get();
String file = settings.getOpenFile();
if (!X_String.isEmptyTrimmed(file)) {
localRequest.setWorkspaceName("Collide");
JsoArray<String> files = JsoArray.create();
files.add(file);
localRequest.setLastOpenFiles(files);
callback.onMessageReceived(localRequest);
}
// If nothing hardcoded in page, ask the server for data
appContext.getFrontendApi().GET_WORKSPACE_META_DATA.send(GetWorkspaceMetaDataImpl.make(), callback);
view.getAwesomeBoxComponentHost().show();
}
private final MapFromStringTo<elemental.html.Window> openWindows = Collections.mapFromStringTo();
@Override
public RemovalHandler openInIframe(String id, String url) {
return view.openIframe(id, url);
}
@Override
public void openInNewWindow(String id, String url) {
elemental.html.Window w;
if (id == null) id = url;
w = openWindows.get(id);
if (w == null || w.isClosed()) {
w = Browser.getWindow();
w.open(url, id);
openWindows.put(id, w);
}else {
w.getLocation().assign(url);
}
}
@Override
public WorkspacePlace getPlace() {
return workspacePlace;
}
@Override
public void initializePlugin(
AppContext appContext, MultiPanel<?, ?> masterPanel, Place currentPlace) {
}
@Override
public ImageResource getIcon(
com.google.collide.client.workspace.Header.Resources res) {
return null;
}
@Override
public void onClicked(ImageButton button) {
}
@Override
public FileAssociation getFileAssociation() {
return null;
}
@Override
public RunConfiguration getRunConfig() {
return null;
}
@Override
public PublicService<?>[] getPublicServices() {
return new PublicService<?>[]{
new PublicService.DefaultServiceProvider<LauncherService>(
LauncherService.class, this)
};
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/demo/child/ChildModule.java | client/src/main/java/collide/demo/child/ChildModule.java | package collide.demo.child;
import collide.demo.shared.SharedClass;
import xapi.annotation.reflect.KeepMethod;
import xapi.log.X_Log;
import xapi.util.X_Util;
import static com.google.gwt.reflect.shared.GwtReflect.magicClass;
import static xapi.util.X_Runtime.isJava;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.reflect.client.strategy.ReflectionStrategy;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.security.CodeSource;
import java.security.ProtectionDomain;
@ReflectionStrategy(debug=ReflectionStrategy.ALL_MEMBERS | ReflectionStrategy.ALL_ANNOTATIONS)
public class ChildModule implements EntryPoint {
public static void main(String[] args) {
new ChildModule().onModuleLoad();
}
@Override
public void onModuleLoad() {
try {
out("Hello world!!!!!\n");
// First, enhance our classes.
magicClass(SharedClass.class);
// Log to console for inspection
out(SharedClass.class);
out("\n");
// Now, play with it a little
SharedClass instance = new SharedClass();
fieldTest(instance);
methodTest(instance);
constructorTest(instance);
codesourceTest(instance);
out("Annotation: ");
out(SharedClass.class.getAnnotation(ReflectionStrategy.class));
sharedObjectTest(instance);
} catch (Throwable e) {
fail(e);
}
}
private final Method out;
ChildModule() {
try {
if (isJava()) {
out = X_Log.class.getMethod("info", Object[].class);
} else {
out = magicClass(ChildModule.class).getDeclaredMethod("jsOut", Object[].class);
}
} catch (Exception e) {
throw X_Util.rethrow(e);
}
}
private void out(Object o) throws Exception {
o = new Object[] { o };
out.invoke(this, o);
}
@KeepMethod
private native void jsOut(Object[] o)
/*-{
$wnd.console.log(o[0])
var pre = $doc.createElement('pre')
pre.innerHTML = o[0]
$doc.body.appendChild(pre)
}-*/;
void fieldTest(SharedClass test) throws Exception {
Field field = SharedClass.class.getField("sharedInt");
out("Field:");
out(field);
out("\n");
int was = test.sharedInt;
out("Changing " + field + " from " + field.get(test) + " to 3;");
field.set(test, 3);
out("See: " + test.sharedInt + " != " + was);
out("\n");
}
void methodTest(SharedClass test) throws Exception {
Method doStuff = test.getClass().getDeclaredMethod("doStuff");
doStuff.setAccessible(true);
doStuff.invoke(test);
out("Method:");
out(doStuff);
out("\n");
}
void constructorTest(SharedClass test) throws Exception {
Constructor<SharedClass> ctor = SharedClass.class.getConstructor();
out("Constructor:");
out(ctor);
SharedClass other = ctor.newInstance();
if (other == null)
throw new RuntimeException("New instance returned null");
assert other != test;
out("\n");
}
void codesourceTest(SharedClass test) throws Exception {
ProtectionDomain pd = test.getClass().getProtectionDomain();
CodeSource cs = pd.getCodeSource();
String loc = cs.getLocation().toExternalForm();
out("Compiled from:");
out(loc);
out("\n");
}
void sharedObjectTest(SharedClass test) {
}
native void sendObject(Class<SharedClass> cls, SharedClass test)
/*-{
$wnd.top.Callback(cls, test);
}-*/;
void fail(Throwable e) {
try{
while (e != null) {
out(e.toString());
for (StackTraceElement el : e.getStackTrace()) {
out(el.toString());
}
e = e.getCause();
}
} catch (Exception ex){ex.printStackTrace();}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/demo/view/SplitPanel.java | client/src/main/java/collide/demo/view/SplitPanel.java | package collide.demo.view;
import collide.client.util.CssUtils;
import collide.demo.resources.DemoResources;
import collide.plugin.client.inspector.ElementInspector;
import com.google.collide.json.client.JsoArray;
import elemental.client.Browser;
import elemental.dom.Document;
import elemental.dom.Element;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.events.EventRemover;
import elemental.events.MouseEvent;
import elemental.util.Timer;
import xapi.log.X_Log;
import xapi.util.api.RemovalHandler;
import com.google.gwt.resources.client.CssResource;
import java.util.Comparator;
import java.util.TreeMap;
public class SplitPanel {
public static interface Css extends CssResource{
String splitPanel();
String splitPanelChild();
String panelContent();
String verticalSplit();
String head();
String horizontalSplit();
String bottomSplit();
String leftSplit();
String rightSplit();
String tail();
String topSplit();
}
class PanelNode {
Element el;
PanelNode next;
double size;
}
final PanelNode head;
PanelNode tail;
int size;
private boolean vertical;
private Timer refresh;
private Css css;
public SplitPanel(boolean vertical) {
this.vertical = vertical;
css = createCss();
tail = head = new PanelNode();
head.el = Browser.getDocument().createDivElement();
head.el.addClassName(css.splitPanel());
head.el.addClassName(vertical ? css.verticalSplit() : css.horizontalSplit());
}
public Element getElement() {
return head.el;
}
public RemovalHandler addChild(Element child, double width) {
return addChild(child, width, -1);
}
public RemovalHandler addChild(final Element child, double width, int index) {
if (exists(child)) {
// TODO adjust index
return RemovalHandler.DoNothing;
}
final PanelNode node = new PanelNode();
node.size = width;
node.el = wrapChild(child, node);
getElement().appendChild(node.el);
RemovalHandler remover = new RemovalHandler() {
@Override
public void remove() {
SplitPanel.this.remove(node);
}
};
size ++;
if (index < 0) {
// Negative index = add-to-end, the simplest and fastest case.
tail.next = node;
tail.el.removeClassName(css.tail());
node.el.addClassName(css.tail());
if (tail == head) {
node.el.addClassName(css.head());
}
tail = node;
} else {
PanelNode target = head;
while (index --> 0) {
if (target.next==null)
break;
target = target.next;
}
if (target.next == null) {
// We hit the end, add to end and update tail
target.next = node;
tail.el.removeClassName(css.tail());
node.el.addClassName(css.tail());
if (tail == head) {
node.el.addClassName(css.head());
}
tail = node;
} else {
// An actual insert, just update pointers
if (target == head) {
if (head.next != null) {
head.next.el.removeClassName(css.head());
}
node.el.addClassName(css.head());
}
node.next = target.next;
target.next = node;
}
}
if (refresh == null) {
refresh = new Timer() {
@Override
public void run() {
refresh = null;
refresh();
}
};
refresh.schedule(1);
}
return remover;
}
public void remove(Element el) {
PanelNode node = head;
while (node != null) {
if (node.el == el) {
remove(node);
return;
}
node = node.next;
}
}
private void remove(PanelNode node) {
if (head.next == node) {
node.el.removeClassName(css.head());
node.el.removeFromParent();
if (node.next != null) {
node.next.el.addClassName(css.head());
}
head.next = node.next;
if (isElastic(node)) {
giveSpace(node.size);
}
size--;
refresh();
return;
}
PanelNode target = head;
while (target.next != null) {
if (target.next == node) {
if (node == tail) {
node.el.removeClassName(css.tail());
target.el.addClassName(css.tail());
tail = target;
}
node.el.removeFromParent();
target.next = node.next;
if (isElastic(node)) {
giveSpace(node.size);
}
size--;
refresh();
return;
}
target = target.next;
}
}
private void giveSpace(double size) {
PanelNode search = head.next;
while (search != null) {
if (isElastic(search)) {
search.size += size;
return;
}
search = search.next;
}
}
private boolean exists(Element child) {
PanelNode search = head.next;
while (search != null) {
if (search.el == child)
return true;
search = search.next;
}
return false;
}
protected int getMaxDimension() {
return vertical ? head.el.getClientHeight() : head.el.getClientWidth();
}
public void refresh() {
if (head.next == null)
return;
// Layout panels.
PanelNode node = head;
double percents = 0;
double px = 0;
float max = getMaxDimension();
JsoArray<PanelNode> fills = JsoArray.create();
JsoArray<PanelNode> fixed = JsoArray.create();
while (node.next != null) {
node = node.next;
if (node.size < 0)
fills.add(node);
else {
fixed.add(node);
if (node.size < 1){
assert node.size != 0;
percents += node.size;
}
else
px += node.size;
}
}
final int numFills = fills.size();
final int numFixed = fixed.size();
double x = 0;
boolean overflow = false;
if (numFixed == 0) {
// No fixed size items, just lay everything out evenly.
double w = max / numFills;
for (int i = 0; i < numFills; i++)
x = setSize(fills.get(i), w, x);
} else {
// Some fixed / percent size items.
double size = px + percents * max;
double scale = size / max;
if (numFills == 0) {
// No fills, distribute proportionally
for (int i = 0;i < numFixed; i++) {
PanelNode child = fixed.get(i);
x = setSize(child, (child.size < 1 ? size * child.size : child.size) / scale, x);
}
} else {
// Some fixed, some fills; things could get messy...
double fillSize;
overflow = scale > 1;
if (overflow) {
// We have an effin' mess! Just scroll everything off the end
fillSize = max * .25; // Fills get 25% screen size
scale = 1; // Everything else gets what it asked for
size = max;
} else {
// There's enough to give everyone what they want, and give the rest to fills.
fillSize = Math.max(350, (max - size) / numFills);
}
node = head; // We have to iterate all nodes
while (node.next != null) {
node = node.next;
if (node.size < 0) {
// A fill. Give it our leftover size
x = setSize(node, fillSize, x);
} else if (node.size < 1) {
// A percent. Give it a ratio of max
x = setSize(node, node.size * size
// size / scale
, x);
} else {
// A fixed size. Scale it up / down.
x = setSize(node, node.size, x);
}
}
}
enableOverflow(overflow);
}
}
protected Element wrapChild(Element child, PanelNode node) {
ElementInspector.get().makeInspectable(child, node);
// Throw in some drag handles.
Document doc = Browser.getDocument();
Element wrapper = doc.createDivElement();
child.addClassName(css.panelContent());
wrapper.addClassName(css.splitPanelChild());
wrapper.getStyle().setPosition("absolute");
wrapper.appendChild(child);
createSlider(wrapper, child, node, true);
createSlider(wrapper, child, node, false);
return wrapper;
}
private Css createCss() {
Css css = DemoResources.GLOBAL.splitPanel();
css.ensureInjected();
return css;
}
static class PanelPosition {
float posStart;
float sizeStart;
float mouseStart;
PanelNode node;
PanelPosition next;
}
private void createSlider(final Element wrapper, final Element child,
final PanelNode node, final boolean first) {
final Element sliderEl = Browser.getDocument().createSpanElement();
final String cls;
if (vertical) {
if (first) {
// Do a top-slider
cls = css.topSplit();
} else {
// Do a bottom-slider
cls = css.bottomSplit();
}
} else {
if (first) {
// Do a left-slider
cls = css.leftSplit();
} else {
// Do a right-slider
cls = css.rightSplit();
}
}
sliderEl.addClassName(cls);
wrapper.appendChild(sliderEl);
final PanelPosition self = new PanelPosition();
self.node = node;
sliderEl.setOnmousedown(new EventListener() {
@Override
public void handleEvent(Event evt) {
evt.preventDefault();
final PanelNode siblingNode = first ? getPreviousSibling(node) : node.next;
final Element sibling;
if (siblingNode == null) {
sibling = null;
} else {
self.next = new PanelPosition();
sibling = siblingNode.el;
self.next.node = siblingNode;
}
PanelPosition affected = self.next;
MouseEvent e = (MouseEvent) evt;
if (vertical) {
self.mouseStart = e.getClientY();
// We parse from the css values set (which we set before this is called),
// so we don't have to do any measuring
// or compensate for weird offsets in the client elements.
self.posStart = CssUtils.parsePixels(wrapper.getStyle().getTop());
self.sizeStart = CssUtils.parsePixels(wrapper.getStyle().getHeight());
if (sibling != null) {
affected.posStart = CssUtils.parsePixels(sibling.getStyle().getTop());
affected.sizeStart = CssUtils.parsePixels(sibling.getStyle().getHeight());
}
} else {
self.mouseStart = e.getClientX();
self.posStart = CssUtils.parsePixels(wrapper.getStyle().getLeft());
self.sizeStart = CssUtils.parsePixels(wrapper.getStyle().getWidth());
if (sibling != null) {
affected.posStart = CssUtils.parsePixels(sibling.getStyle().getLeft());
affected.sizeStart = CssUtils.parsePixels(sibling.getStyle().getWidth());
}
}
final EventRemover[] remover = new EventRemover[2];
// TODO put these event listeners over an empty iframe, to cover up any iframes on page.
remover[0] = Browser.getWindow().addEventListener("mouseup", new EventListener() {
@Override
public void handleEvent(Event evt) {
if (remover[0] != null){
remover[0].remove();
remover[1].remove();
onResizeFinished(siblingNode, self);
remover[0] = null;
}
}
}, true);
remover[1] = Browser.getWindow().addEventListener("mousemove", new EventListener() {
@Override
public void handleEvent(Event evt) {
evt.preventDefault();
final MouseEvent e = (MouseEvent) evt;
final Element el = self.next == null ? null : self.next.node.el;
assert el != wrapper;
double delta;
if (vertical) {
delta = e.getClientY() - self.mouseStart;
if (first) {
// A top drag affects top and height
wrapper.getStyle().setTop((int)(self.posStart+ delta),"px");
wrapper.getStyle().setHeight((int)(self.sizeStart - delta),"px");
if (el != null) {
// TODO implement max/min/pref values, and iterate through the
// nodes to push delta off on any neighbors
el.getStyle().setHeight((int)(self.next.sizeStart + delta),"px");
}
} else {
wrapper.getStyle().setHeight((int)(self.sizeStart + delta),"px");
if (el != null) {
el.getStyle().setTop((int)(self.next.posStart+ delta),"px");
el.getStyle().setHeight((int)(self.next.sizeStart - delta),"px");
}
}
} else {
delta = e.getClientX() - self.mouseStart;
if (first) {
// A left drag affects left and size
wrapper.getStyle().setLeft((int)(self.posStart + delta),"px");
wrapper.getStyle().setWidth((int)(self.sizeStart - delta),"px");
if (el != null) {
el.getStyle().setWidth((int)(self.next.sizeStart + delta),"px");
}
} else {
wrapper.getStyle().setWidth((int)(self.sizeStart + delta),"px");
if (el != null) {
el.getStyle().setLeft((int)(self.next.posStart + delta),"px");
el.getStyle().setWidth((int)(self.next.sizeStart - delta),"px");
}
}
}
}
}, true);
}
});
}
private void onResizeFinished(PanelNode siblingNode, PanelPosition self) {
if (self.node.size < 1) {
if (self.node.size > 0) {
// A fractional panel should get it's fraction updated
double size = getSize(self.node),
max = getMaxDimension(),
current = size / max,
is = self.node.size,
delta = is - current;
X_Log.info("Resize done; was ",self.node.size, " is ",current);
self.node.size = current;
stealSize(self.node, delta);
}
}
}
private static final Comparator<Double> cmp = new Comparator<Double>() {
@Override
public int compare(Double o1, Double o2) {
return o1 < o2 ? 1 : -1; // largest to smallest
}
};
private void stealSize(PanelNode node, double delta) {
PanelNode search = head;
TreeMap<Double, PanelNode> areElastic = new TreeMap<Double, PanelNode>(cmp);
do {
if (isElastic(search)) {
if (search != node) {
areElastic.put(search.size, search);
}
}
search = search.next;
} while (search != null);
int size = areElastic.size();
if (size == 0) {
return;
}
X_Log.info(getClass(), "Stealing size ", delta, " for ", node,"from",areElastic.values().toArray());
if (size == 1) {
PanelNode from = areElastic.values().iterator().next();
double was = from.size
,is = 1 - node.size,
round = is - Math.floor(10000.0 * is)/10000.0;
from.size = is > from.size ? is - round : is + round;
X_Log.info("Size changed from ", was, "to", from.size, "for",from);
return;
}
double[] avail = new double[size];
int pos = 0;
for (PanelNode from : areElastic.values()) {
if (from.size <= 0.1) {
continue;
}
double has = from.size + delta;
if (has > 1) {
has = has - 1;
// has = has - 1;
// if (has)
} else if (0 > has) {
avail[pos] = 0;
} else {
avail[pos] = from.size - has;
}
pos ++;
}
}
protected boolean isElastic(PanelNode search) {
return search.size > 0 && search.size < 1;
}
private double getSize(PanelNode node) {
return vertical
? node.el.getClientHeight()
: node.el.getClientWidth();
}
private PanelNode getPreviousSibling(PanelNode node) {
if (node == head.next)
return null;
PanelNode search = head;
while (search.next != null) {
if (search.next == node) {
return search;
}
search = search.next;
}
return null;
}
private void enableOverflow(boolean enable) {
if (enable) {
if (vertical) {
head.el.getStyle().setOverflowY("auto");
} else {
head.el.getStyle().setOverflowX("auto");
}
} else {
if (vertical) {
head.el.getStyle().clearOverflowY();
} else {
head.el.getStyle().clearOverflowX();
}
}
}
private double setSize(PanelNode panelNode, double w, double x) {
if (vertical) {
panelNode.el.getStyle().setHeight((int)w, "px");
panelNode.el.getStyle().setTop((int)x, "px");
} else {
panelNode.el.getStyle().setWidth((int)w, "px");
panelNode.el.getStyle().setLeft((int)x, "px");
}
return x+w;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/demo/view/TabPanel.java | client/src/main/java/collide/demo/view/TabPanel.java | package collide.demo.view;
import xapi.inject.impl.SingletonProvider;
import xapi.log.X_Log;
import xapi.util.api.HasId;
import collide.client.util.Elements;
import collide.demo.view.TabPanel.TabView;
import collide.gwtc.resources.GwtcCss;
import com.google.collide.client.ui.panel.PanelContent;
import com.google.collide.client.ui.panel.PanelContent.AbstractContent;
import com.google.collide.json.client.JsoStringMap;
import com.google.collide.mvp.CompositeView;
import com.google.collide.mvp.UiComponent;
import com.google.collide.mvp.View;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.user.client.ui.HasText;
import elemental.dom.Element;
import elemental.events.Event;
import elemental.events.EventListener;
import elemental.html.DivElement;
public class TabPanel extends UiComponent<View<?>> implements PanelContent{
public static final SingletonProvider<TabPanelResources> DEFAULT_RESOURCES =
new SingletonProvider<TabPanelResources>() {
protected TabPanelResources initialValue() {
TabPanelResources res = GWT.create(TabPanelResources.class);
res.css().ensureInjected();
return res;
};
};
public static TabPanel create(TabPanelResources res) {
return new TabPanel(res);
}
public static class TabPanelView extends CompositeView<Void> {
public TabPanelView(TabPanelResources res) {
setElement(Elements.createDivElement(res.css().tabPanel(),res.css().hidden()));
}
}
public class TabView extends CompositeView<Void> {
private final DivElement tabHeader;
private final DivElement tabBody;
private final String id;
public TabView(String id) {
this.id = id;
tabHeader = Elements.createDivElement(css.tabHeader());
header.appendChild(tabHeader);
tabBody = Elements.createDivElement(css.hidden());
body.appendChild(tabBody);
}
public void setContent(View<?> view, String title) {
tabBody.setInnerHTML("");
tabBody.appendChild(view.getElement());
tabHeader.setInnerHTML("");
Element head = buildTabHeader(title);
tabHeader.appendChild(head);
attachHandler(this, tabHeader);
}
}
private final JsoStringMap<TabView> panels;
private final Element header;
private final Element body;
private final TabPanelCss css;
private TabView selected;
public TabPanel(TabPanelResources res) {
super(new TabPanelView(res));
css = res.css();
panels = JsoStringMap.create();
header = Elements.createDivElement(css.tabBar());
getView().getElement().appendChild(header);
body = Elements.createDivElement(css.tabBody());
getView().getElement().appendChild(body);
}
public void attachHandler(final TabView tabView, final Element head) {
DivElement el = Elements.createDivElement(css.closeIcon());
el.setOnclick(new EventListener() {
@Override
public void handleEvent(Event evt) {
remove(tabView);
}
});
head.setOnclick(new EventListener() {
@Override
public void handleEvent(Event evt) {
if (panels.containsKey(tabView.id)) {
select(tabView);
}
}
});
head.appendChild(el);
}
protected void remove(TabView tabView) {
tabView.tabBody.removeFromParent();
tabView.tabHeader.removeFromParent();
panels.remove(tabView.id);
if (panels.isEmpty()) {
getContentElement().addClassName(css.hidden());
} else {
if (selected == tabView) {
if (selectById(panels.getKeys().get(0))) {
return;
}
selected = null;
}
}
}
private boolean selectById(String id) {
TabView panel = panels.get(id);
if (panel == null) {
X_Log.warn(getClass(), "Tried to select panel with id",id,"but no panel with that id is attached");
return false;
} else {
select(panel);
return true;
}
}
public void select(TabView tabView) {
if (selected != null) {
selected.tabHeader.removeClassName(css.selected());
selected.tabBody.addClassName(css.hidden());
}
selected = tabView;
selected.tabHeader.addClassName(css.selected());
selected.tabBody.removeClassName(css.hidden());
}
public Element buildTabHeader(String title) {
DivElement el = Elements.createDivElement();
el.setInnerHTML(title);
return el;
}
public <V extends com.google.collide.mvp.View<?> & HasId> TabView addContent(V view) {
final String title;
if (view instanceof HasText) {
title = ((HasText)view).getText();
} else {
title = view.getId();
}
TabView existing = panels.get(view.getId());
if (existing == null) {
existing = createPanel(view, title);
panels.put(view.getId(), existing);
}
if (selected == null) {
select(existing);
}
existing.setContent(view, title);
getContentElement().removeClassName(css.hidden());
return existing;
}
protected <V extends com.google.collide.mvp.View<?> & HasId> TabView createPanel(V view, String title) {
return new TabView(view.getId());
}
@Override
public Element getContentElement() {
return getView().getElement();
}
@Override
public void onContentDisplayed() {
}
@Override
public void onContentDestroyed() {
}
public boolean unhide(TabView tabView) {
if (tabView.tabHeader.getParentElement() == null) {
tabView.tabHeader.addClassName(css.selected());
tabView.tabBody.removeClassName(css.hidden());
getView().getElement().removeClassName(css.hidden());
panels.put(tabView.id, tabView);
header.appendChild(tabView.tabHeader);
body.appendChild(tabView.tabBody);
return true;
}
return false;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/demo/view/TabPanelCss.java | client/src/main/java/collide/demo/view/TabPanelCss.java | package collide.demo.view;
import com.google.gwt.resources.client.CssResource;
public interface TabPanelCss extends CssResource {
String tabBar();
String selected();
String hidden();
String tabHeader();
String tabBody();
String tabPanel();
String closeIcon();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/demo/view/TabController.java | client/src/main/java/collide/demo/view/TabController.java | package collide.demo.view;
public interface TabController {
public void closeTab(String id);
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/demo/view/PanelController.java | client/src/main/java/collide/demo/view/PanelController.java | package collide.demo.view;
public interface PanelController {
void doMinimize();
void doClose();
void doMaximize();
// To let subclasses call into custom functionality
void callPlugin(Class<?> pluginClass, Object ... args);
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/demo/view/DemoView.java | client/src/main/java/collide/demo/view/DemoView.java | package collide.demo.view;
import collide.client.util.Elements;
import collide.gwtc.GwtCompileStatus;
import collide.gwtc.GwtcController;
import collide.gwtc.ui.GwtCompilePlace;
import collide.gwtc.ui.GwtCompilerShell;
import collide.gwtc.ui.GwtStatusListener;
import collide.gwtc.view.GwtcModuleControlView;
import collide.plugin.client.standalone.StandaloneConstants;
import collide.plugin.client.terminal.TerminalLogView;
import com.google.collide.client.code.FileContent;
import com.google.collide.client.search.awesomebox.host.AwesomeBoxComponentHost;
import com.google.collide.client.ui.panel.MultiPanel;
import com.google.collide.client.ui.panel.PanelContent;
import com.google.collide.client.ui.panel.PanelModel;
import com.google.collide.client.ui.panel.PanelModel.Builder;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.workspace.Header;
import com.google.collide.client.workspace.WorkspaceShell;
import com.google.collide.dto.CompileResponse;
import com.google.collide.dto.CompileResponse.CompilerState;
import com.google.collide.dto.client.DtoClientImpls.GwtRecompileImpl;
import com.google.collide.mvp.ShowableUiComponent;
import com.google.collide.mvp.UiComponent;
import elemental.client.Browser;
import elemental.dom.Document;
import elemental.dom.Element;
import elemental.html.DivElement;
import elemental.html.IFrameElement;
import elemental.util.Collections;
import elemental.util.MapFromStringTo;
import xapi.log.X_Log;
import xapi.util.api.RemovalHandler;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.ext.TreeLogger.Type;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.user.client.Window;
class ControllerView extends com.google.collide.client.ui.panel.MultiPanel.View<PanelModel>
{
Element header, core;
public ControllerView(Element element, boolean detached) {
super(element, detached);
header = Browser.getDocument().createDivElement();
element.appendChild(header);
core = Browser.getDocument().createDivElement();
element.appendChild(core);
}
@Override
public Element getContentElement() {
return core;
}
@Override
public Element getHeaderElement() {
return header;
}
}
public class DemoView
extends MultiPanel<PanelModel, ControllerView>
{
private Element browser, editor, compiler, headerEl;
private ShowableUiComponent<?> bar;
private final SplitPanel middleBar;
private final SplitPanel bottomBar;
private final SplitPanel verticalSplit;
private Header header;
public DemoView() {
super(new ControllerView(findBody(), true));
middleBar = new SplitPanel(false);
bottomBar = new SplitPanel(false);
verticalSplit = new SplitPanel(true);
headerEl = Browser.getDocument().createDivElement();
headerEl.getStyle().setHeight(58, "px");
Browser.getDocument().getBody().appendChild(headerEl);
Element el = getView().getElement();
el.getStyle().setTop(58, "px");
verticalSplit.addChild(middleBar.getElement(), 0.6);
verticalSplit.addChild(bottomBar.getElement(), 0.4);
el.appendChild(verticalSplit.getElement());
bar = new ShowableUiComponent<View<?>>() {
// We aren't using the toolbar just yet.
@Override
public void doHide() {
}
@Override
public void doShow() {
}
};
browser = createElement(-1, 350);
browser.setId(StandaloneConstants.FILES_PANEL);
editor = createElement(-1, -1);
editor.setId(StandaloneConstants.WORKSPACE_PANEL);
compiler = Browser.getDocument().createDivElement();
bottomBar.addChild(compiler, 650);
attachHandlers();
}
protected void attachHandlers() {
Window.addResizeHandler(new ResizeHandler() {
@Override
public void onResize(ResizeEvent event) {
verticalSplit.refresh();
middleBar.refresh();
bottomBar.refresh();
}
});
}
private Element createElement(int index, double width) {
DivElement el = Browser.getDocument().createDivElement();
middleBar.addChild(el, width);
return el;
}
private static Element findBody() {
Document doc = Browser.getDocument();
Element body = doc.getElementById("gwt_root");
return body == null ? doc.getBody() : body;
}
private void append(Element element) {
if (element.hasClassName("middle")) {
middleBar.addChild(wrapChild(element), 0.25);
} else {
bottomBar.addChild(wrapChild(element), -1);
}
}
public void append(UiComponent<?> element) {
Element el = wrapChild(element.getView().getElement());
if (element instanceof WorkspaceShell) {
browser.appendChild(el);
} else if (element instanceof GwtCompilerShell) {
compiler.appendChild(el);
} else if (element instanceof Header) {
header = (Header)element;
headerEl.appendChild(element.getView().getElement());
} else if (element instanceof TabPanel) {
append(((TabPanel) element).getContentElement());
} else {
X_Log.warn("Unknown element type",element);
getView().getElement().appendChild(el);
}
}
private Element wrapChild(Element element) {
return element;
}
FileContent file;
@Override
public void setContent(PanelContent panelContent) {
setContent(panelContent, null);
}
@Override
public void setContent(PanelContent panelContent, PanelModel settings) {
X_Log.info("PanelController content set",panelContent);
if (panelContent instanceof FileContent) {
if (file != null) {
PathUtil path = file.filePath();
if (path != null && !path.equals(((FileContent) panelContent).filePath())){
minimizeFile(path);
}
file.onContentDestroyed();
}
file = (FileContent)panelContent;
// Ideally, we would reuse our uibinder instead of just clearing this
editor.getFirstChildElement().getLastElementChild().setInnerHTML("");
editor.getFirstChildElement().getLastElementChild().appendChild(file.getContentElement());
} else if (panelContent instanceof TerminalLogView) {
// TODO use a tab panel wrapper for log viewers
bottomBar.addChild(panelContent.getContentElement(), 500, 1);
} else if (panelContent instanceof GwtCompilerShell){
// Element el = wrapChild(((UiComponent<?>)panelContent).getView().getElement());
// bottomBar.addChild(el, 0.3);
} else if (panelContent instanceof UiComponent){
append((UiComponent<?>)panelContent);
} else {
X_Log.warn("Unhandled panel type: ",panelContent.getClass(), panelContent);
append(panelContent.getContentElement());
throw new RuntimeException();
}
panelContent.onContentDisplayed();
}
public void minimizeFile(final PathUtil path) {
DivElement el = Browser.getDocument().createDivElement();
}
@Override
public ShowableUiComponent<?> getToolBar() {
return bar;
}
private static final class GwtCompileState {
IFrameElement el;
GwtCompileStatus status = GwtCompileStatus.Pending;
Type logLevel = Type.ALL;
public GwtcModuleControlView header;
}
private final MapFromStringTo<GwtCompileState> compileStates = Collections.mapFromStringTo();
private GwtCompilerShell gwt;
public RemovalHandler openIframe(final String id, final String url) {
final GwtCompileState gwtc = getCompileState(id);
IFrameElement iframe = gwtc.el;
if (iframe == null) {
DivElement sizer = Elements.createDivElement();
sizer.getStyle().setPosition("absolute");
sizer.getStyle().setLeft("0px");
sizer.getStyle().setRight("10px");
sizer.getStyle().setTop("50px");
sizer.getStyle().setBottom("20px");
gwtc.el = iframe = Browser.getDocument().createIFrameElement();
iframe.getStyle().setWidth("100%");
iframe.getStyle().setHeight("100%");
iframe.setAttribute("sandbox", "allow-same-origin allow-scripts allow-top-navigation");
iframe.setSrc(url);
sizer.appendChild(iframe);
final RemovalHandler[] remover = new RemovalHandler[1];
gwtc.header = GwtcModuleControlView.create(new GwtcController() {
@Override
public void onReloadClicked() {
GwtCompilePlace.PLACE.fireRecompile(id);
}
@Override
public void onCloseClicked() {
if (remover[0] != null) {
removeCompileState(id);
remover[0].remove();
remover[0] = null;
}
}
@Override
public void onRefreshClicked() {
gwtc.el.setSrc(url);
}
});
Element wrapper = gwtc.header.getElement();
gwtc.header.setHeader(id);
wrapper.appendChild(sizer);
wrapper.getStyle().setOverflow("hidden");
remover[0] = middleBar.addChild(wrapper, 450, 2);
} else {
iframe.setSrc("about:blank");
iframe.setSrc(url);
}
iframe.scrollIntoViewIfNeeded(true);
return new RemovalHandler() {
@Override
public void remove() {
removeCompileState(id);
}
};
}
protected GwtCompileState getCompileState(String id) {
GwtCompileState state = compileStates.get(id);
if (state == null) {
state = new GwtCompileState();
compileStates.put(id, state);
}
return state;
}
protected void removeCompileState(String id) {
compileStates.remove(id);
// TODO kill any active compiles?
}
@Override
public Builder<PanelModel> newBuilder() {
return defaultBuilder();
}
public void initGwt(final GwtCompilerShell gwt) {
this.gwt = gwt;
gwt.addCompileStateListener(new GwtStatusListener() {
@Override
@SuppressWarnings("incomplete-switch")
public void onLogLevelChange(String module, Type level) {
GwtCompileState gwtc = getCompileState(module);
gwtc.logLevel = level;
switch (level) {
case ERROR:
gwtc.status = GwtCompileStatus.Fail;
if (gwtc.header != null) {
gwtc.header.setCompileStatus(gwtc.status);
}
break;
case WARN:
gwtc.status = GwtCompileStatus.Warn;
if (gwtc.header != null) {
gwtc.header.setCompileStatus(gwtc.status);
}
break;
}
}
@Override
public void onGwtStatusUpdate(CompileResponse status) {
GwtCompileState gwtc = getCompileState(status.getModule());
CompilerState state = status.getCompilerStatus();
X_Log.info(getClass(), "State change",status.getModule(),state);
switch (state) {
case FAILED:
gwtc.status = GwtCompileStatus.Fail;
if (gwtc.header != null) {
gwtc.header.setCompileStatus(gwtc.status);
}
break;
case FINISHED:
case SERVING:
if (gwtc.logLevel.ordinal() == Type.ERROR.ordinal()) {
gwtc.status = GwtCompileStatus.PartialSuccess;
} else {
gwtc.status = GwtCompileStatus.Success;
}
gwtc.logLevel = Type.WARN;
if (gwtc.header != null) {
gwtc.header.setCompileStatus(gwtc.status);
}
break;
case RUNNING:
gwtc.status = GwtCompileStatus.Good;
if (gwt.isAutoOpen()) {
GwtRecompileImpl value = gwt.getValue();
String key = status.getStaticName() == null ? value.getModule() : status.getStaticName();
gwt.setMessageKey(value.getModule(), key);
gwt.getView().getDelegate().openIframe(key, value.getPort());
}
if (gwtc.header != null) {
gwtc.header.setCompileStatus(gwtc.status);
}
case BLOCKING:
case UNLOADED:
}
}
});
append(gwt);
}
public AwesomeBoxComponentHost getAwesomeBoxComponentHost() {
return header.getAwesomeBoxComponentHost();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/demo/view/TabPanelResources.java | client/src/main/java/collide/demo/view/TabPanelResources.java | package collide.demo.view;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.ImageResource;
public interface TabPanelResources extends ClientBundle {
@Source("TabView.css")
TabPanelCss css();
@Source("close.png")
ImageResource closeIcon();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/demo/parent/ParentModule.java | client/src/main/java/collide/demo/parent/ParentModule.java | package collide.demo.parent;
import collide.client.util.Elements;
import collide.demo.controller.DemoController;
import collide.demo.view.DemoView;
import collide.gwtc.ui.GwtCompilerService;
import collide.gwtc.ui.GwtCompilerShell;
import collide.gwtc.ui.GwtCompilerShell.Resources;
import collide.plugin.client.launcher.LauncherService;
import collide.plugin.client.terminal.TerminalService;
import com.google.collide.client.AppContext;
import com.google.collide.client.CollideBootstrap;
import com.google.collide.client.communication.FrontendApi.ApiCallback;
import com.google.collide.client.history.Place;
import com.google.collide.client.plugin.ClientPlugin;
import com.google.collide.client.plugin.ClientPluginService;
import com.google.collide.client.plugin.FileAssociation;
import com.google.collide.client.plugin.RunConfiguration;
import com.google.collide.client.status.StatusManager;
import com.google.collide.client.status.StatusMessage;
import com.google.collide.client.ui.button.ImageButton;
import com.google.collide.client.ui.panel.MultiPanel;
import com.google.collide.client.workspace.Header;
import com.google.collide.client.workspace.WorkspacePlace;
import com.google.collide.clientlibs.model.Workspace;
import com.google.collide.dto.GwtRecompile;
import com.google.collide.dto.GwtSettings;
import com.google.collide.dto.ServerError.FailureReason;
import com.google.collide.shared.plugin.PublicService;
import com.google.collide.shared.plugin.PublicServices;
import com.google.gwt.resources.client.ImageResource;
import elemental.client.Browser;
import elemental.html.ScriptElement;
import xapi.log.X_Log;
import xapi.util.api.SuccessHandler;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.RunAsyncCallback;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.user.client.Window;
/**
* This demo class shows how to use gwt reflection to send
* dtos across different compilations of gwt,
* as if the objects were merely loaded by a different classloader.
*
* @author "James X. Nelson (james@wetheinter.net)"
*
*/
public class ParentModule implements EntryPoint{
@Override
public void onModuleLoad() {
// First, let's setup a callback for child modules to talk to us
setupNatives();
// Now, let's bootstrap collide
startCollide();
}
private void startCollide() {
GWT.runAsync(AppContext.class, new RunAsyncCallback() {
@Override
public void onSuccess() {
CollideBootstrap.start(new SuccessHandler<AppContext>() {
@Override
public void onSuccess(AppContext context) {
DemoView body = new DemoView();
ClientPluginService plugins = ClientPluginService.initialize
(context, body, WorkspacePlace.PLACE);
addGwtCompiler(context, body);
addEditor(context, body, plugins);
addTerminal(context, body);
}
});
}
@Override
public void onFailure(Throwable reason) {
warn(reason, "Loading Collide's AppContext ");
}
});
}
private void addTerminal(final AppContext context, DemoView body) {
//GWT.runAsync(TerminalService.class, new RunAsyncCallback() {
// @Override
// public void onSuccess() {
//
// }
//
// @Override
// public void onFailure(Throwable reason) {
// warn(reason, "Loading Collide logger ");
// }
//});
}
private void addEditor(final AppContext context, final DemoView body, final ClientPluginService plugins) {
//GWT.runAsync(DemoController.class, new RunAsyncCallback() {
// @Override
// public void onSuccess() {
new DemoController(context).initialize(body, plugins);
// }
//
// @Override
// public void onFailure(Throwable reason) {
// warn(reason, "Loading Collide workspace ");
// }
//});
}
private void addGwtCompiler(final AppContext context, final DemoView body) {
//GWT.runAsync(GwtRecompile.class, new RunAsyncCallback() {
// @Override
// public void onSuccess() {
// Inject css
Resources res = GWT.create(Resources.class);
res.gwtCompilerCss().ensureInjected();
res.gwtLogCss().ensureInjected();
res.gwtClasspathCss().ensureInjected();
res.gwtModuleCss().ensureInjected();
// Prepare view
GwtCompilerService gwtCompiler = PublicServices.getService(GwtCompilerService.class);
final GwtCompilerShell gwt = gwtCompiler.getShell();
// Attach compiler
//body.initGwt(gwt);
ResizeHandler handler = e -> {
Elements.getBody().getStyle().setWidth(Browser.getWindow().getInnerWidth()+"px");
Elements.getBody().getStyle().setHeight(Browser.getWindow().getInnerHeight()+"px");
};
Elements.getBody().getStyle().setPosition("absolute");
Window.addResizeHandler(handler);
handler.onResize(null);
// Request module configs
context.getFrontendApi().GWT_SETTINGS.request(
new ApiCallback<GwtSettings>() {
@Override
public void onFail(FailureReason reason) {
warn(context, "Retrieving gwt settings");
}
@Override
public void onMessageReceived(GwtSettings response) {
gwt.showResults(response);
GwtRecompile defaultModule = response.getModules().get(0);
}
}
);
// }
//
// @Override
// public void onFailure(Throwable reason) {
// warn(reason, "Loading GWT compiler ");
// }
//});
}
private native void setupNatives()
/*-{
$wnd.Callback = function(cls, obj) {
@collide.demo.parent.ParentModule::receiveForeign(*)(cls, obj);
};
}-*/;
public static void receiveForeign(Object cls, Object obj) {
X_Log.info("Received foreign object",cls, obj);
}
private void injectForeignModulue(String src) {
ScriptElement script = Browser.getDocument().createScriptElement();
script.setSrc(src);
Browser.getDocument().getHead().appendChild(script);
}
private void warn(Throwable e, String warning) {
warn((AppContext)null, e+"\n"+warning);
e.printStackTrace();
}
private void warn(AppContext ctx, String warning) {
StatusManager manager = ctx == null ? new StatusManager() : ctx.getStatusManager();
new StatusMessage(manager, StatusMessage.MessageType.ERROR,
warning+" failed in 3 attempts. Try again later.").fire();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/demo/shared/SharedClass.java | client/src/main/java/collide/demo/shared/SharedClass.java | package collide.demo.shared;
import xapi.annotation.compile.MagicMethod;
import xapi.log.X_Log;
import xapi.util.X_Runtime;
import com.google.gwt.reflect.client.strategy.ReflectionStrategy;
import java.io.File;
/**
* This is a test class for our reflection api;
* it is annotated for gwt to pull out reflection data,
* plus it includes different methods for
*
* @author "James X. Nelson (james@wetheinter.net)"
*
*/
@ReflectionStrategy(keepEverything=true, keepCodeSource=true, annotationRetention=ReflectionStrategy.ALL_ANNOTATIONS, debug=ReflectionStrategy.ALL_ANNOTATIONS)
public class SharedClass {
public int sharedInt = 10;
public String sharedString = "stuff";
public void doStuff() throws Exception {
if (X_Runtime.isJava())
doJavaStuff();
else
doJavascriptStuff();
}
private native void doJavascriptStuff()
/*-{
$doc.body.contentEditable=true;
}-*/;
@MagicMethod(doNotVisit = true)
private void doJavaStuff() throws Exception{
X_Log.info("Running in "+
Class.forName("java.io.File").getMethod("getCanonicalPath").invoke(
Class.forName("java.io.File").getConstructor(String.class).newInstance(".")
)
);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/collide/demo/resources/DemoResources.java | client/src/main/java/collide/demo/resources/DemoResources.java | package collide.demo.resources;
import collide.demo.view.SplitPanel;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.resources.client.ClientBundle;
public interface DemoResources extends ClientBundle{
final DemoResources GLOBAL = GWT.create(DemoResources.class);
@Source("SplitPanel.css")
SplitPanel.Css splitPanel();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/mvp/UiComponent.java | client/src/main/java/com/google/collide/mvp/UiComponent.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.mvp;
/**
* This class represents the Presenter (P) in the MVP pattern for constructing
* UI.
*
* The View represents some bag of element references and a definition of
* logical events sources by the View.
*
* The Model is not an explicit entity in this class hierarchy, and is simply a
* name used to refer to the instance state used by the Presenter. Concrete
* implementations may choose to abstract instance state behind an explicit
* Model class if they so choose.
*
* The View can be injected at any point in time.
*
* Presenters contain the logic for handling events sourced by the View,
* updating the Model, and for taking changes to the Model and propagating them
* to the View.
*/
public abstract class UiComponent<V extends View<?>> implements HasView<V> {
private V view;
protected UiComponent() {
this(null);
}
protected UiComponent(V view) {
this.view = view;
}
@Override
public V getView() {
return view;
}
public void setView(V view) {
this.view = view;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/mvp/HasView.java | client/src/main/java/com/google/collide/mvp/HasView.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.mvp;
/**
* An object which has a view.
*/
public interface HasView<V extends View<?>> {
V getView();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/mvp/ShowableUiComponent.java | client/src/main/java/com/google/collide/mvp/ShowableUiComponent.java | package com.google.collide.mvp;
import com.google.collide.shared.util.ListenerManager;
import com.google.collide.shared.util.ListenerRegistrar;
/**
* A {@link UiComponent} which includes {@link #hide()} and {@link #show()} methods.
* @author "James X. Nelson (james@wetheinter.net)"
*
* @param <V>
*/
public abstract class ShowableUiComponent<V extends View<?>> extends UiComponent<V> implements ShowableComponent {
private boolean showing;
private final ListenerRegistrar<ShowStateChangedListener> stateChangeRegistrar;
@Override public final boolean isShowing() {
return showing;
}
/**
* Called to tell your UiComponent to hide or detach
*/
public final void hide() {
if (showing) {
this.showing = false;
doHide();
}
}
public abstract void doHide();
/**
* Called to tell your UiComponent to show or attach
*/
public final void show() {
if (!showing) {
this.showing = true;
doShow();
}
}
public abstract void doShow();
public ShowableUiComponent() {
stateChangeRegistrar = ListenerManager.create();
}
public ShowableUiComponent(V view) {
super(view);
stateChangeRegistrar = ListenerManager.create();
}
@Override
public ListenerRegistrar<ShowStateChangedListener> getShowStateChangedListenerRegistrar() {
return stateChangeRegistrar;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/mvp/ShowableComponent.java | client/src/main/java/com/google/collide/mvp/ShowableComponent.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.mvp;
import com.google.collide.shared.util.ListenerRegistrar;
/**
* A component which can be explicitly shown and hidden. Implementors of this
* interface must callback listeners for at least {@link ShowState#SHOWN} and
* {@link ShowState#HIDDEN}.
*/
public interface ShowableComponent {
/**
* An indicating indicating the show state of a component.
*/
public enum ShowState {
SHOWING, SHOWN, HIDDEN, HIDING
}
/**
* A listener which is notified of changes in the components
* {@link ShowState}.
*/
public interface ShowStateChangedListener {
void onShowStateChanged(ShowState showState);
}
/**
* Displays a component.
*/
public void show();
/**
* Hides a component.
*/
public void hide();
/**
* @return true if the state of the component is logically
* {@link ShowState#SHOWING} or {@link ShowState#SHOWN}.
*/
public boolean isShowing();
public ListenerRegistrar<ShowStateChangedListener> getShowStateChangedListenerRegistrar();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/mvp/CompositeView.java | client/src/main/java/com/google/collide/mvp/CompositeView.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.mvp;
import elemental.dom.Element;
/**
* Wraps an Element that corresponds to some DOM subtree.
*
* This is a View (V) in our use of MVP.
*
* Use this when you want to give some brains to one or more DOM elements by
* making this the View for some {@link UiComponent} that will contain business
* logic.
*
* Implementors may choose to attach event listeners that it needs to DOM
* elements that are contained with this View, and expose logical events where
* appropriate to the containing UiComponent.
*
*/
public abstract class CompositeView<D> implements View<D> {
private Element element;
private D delegate;
/**
* This constructor only exists to support UiBinder which requires us to inject
* the element after the call to the constructor.
*/
protected CompositeView() {
}
protected CompositeView(Element element) {
this.setElement(element);
}
/**
* @return the delegate
*/
@Override
public D getDelegate() {
return delegate;
}
/**
* @return the element
*/
@Override
public Element getElement() {
return element;
}
/**
* @param delegate the delegate to set
*/
@Override
public void setDelegate(D delegate) {
this.delegate = delegate;
}
/**
* @param element the element to set
*/
protected void setElement(Element element) {
this.element = element;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/mvp/View.java | client/src/main/java/com/google/collide/mvp/View.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.mvp;
import elemental.dom.Element;
/**
* Implementors are Objects that represent some DOM structure.
*
*
* @param <D> Generic type representing any class that wishes to become this
* view's delegate and handle events sourced by the view.
*/
public interface View<D> {
/**
* @return the delegate which receives events from this view.
*/
public D getDelegate();
/**
* Sets the delegate to receive events from this view.
*/
public void setDelegate(D delegate);
/**
* @return the base element for this view.
*/
public Element getElement();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/dto/client/DtoUtils.java | client/src/main/java/com/google/collide/dto/client/DtoUtils.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.dto.client;
import com.google.collide.dto.RoutingTypes;
import com.google.collide.dtogen.shared.ServerToClientDto;
import com.google.collide.json.client.Jso;
/**
* Utilities to simplify working with DTOs.
*/
public class DtoUtils {
/**
* Deserializes a string into a DTO of type {@code T}.
*
* @param types list of the deserialized DTO's expected types; should
* generally be one or more of of the constants declared in
* {@link RoutingTypes}.
*/
@SuppressWarnings("unchecked")
public static <T> T parseAsDto(String payload, int... types) {
ServerToClientDto responseData = (ServerToClientDto) Jso.deserialize(payload);
for (int type : types) {
if (responseData.getType() == type) {
return (T) responseData;
}
}
throw new IllegalArgumentException("Unexpected dto type " + responseData.getType());
}
private DtoUtils() {
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/dto/client/ClientDocOpFactory.java | client/src/main/java/com/google/collide/dto/client/ClientDocOpFactory.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.dto.client;
import static com.google.collide.dto.DocOpComponent.Type.DELETE;
import static com.google.collide.dto.DocOpComponent.Type.INSERT;
import static com.google.collide.dto.DocOpComponent.Type.RETAIN;
import static com.google.collide.dto.DocOpComponent.Type.RETAIN_LINE;
import com.google.collide.dto.DocOp;
import com.google.collide.dto.DocOpComponent;
import com.google.collide.dto.DocOpComponent.Delete;
import com.google.collide.dto.DocOpComponent.Insert;
import com.google.collide.dto.DocOpComponent.Retain;
import com.google.collide.dto.DocOpComponent.RetainLine;
import com.google.collide.dto.client.DtoClientImpls.DeleteImpl;
import com.google.collide.dto.client.DtoClientImpls.DocOpImpl;
import com.google.collide.dto.client.DtoClientImpls.InsertImpl;
import com.google.collide.dto.client.DtoClientImpls.RetainImpl;
import com.google.collide.dto.client.DtoClientImpls.RetainLineImpl;
import com.google.collide.dto.shared.DocOpFactory;
import com.google.collide.json.client.JsoArray;
// TODO: These should be moved to an Editor2-specific package
/**
*/
public final class ClientDocOpFactory implements DocOpFactory {
public static final ClientDocOpFactory INSTANCE = new ClientDocOpFactory();
private ClientDocOpFactory() {
}
@Override
public Delete createDelete(String text) {
return (Delete) DeleteImpl.make().setText(text).setType(DELETE);
}
@Override
public DocOp createDocOp() {
return DocOpImpl.make().setComponents(JsoArray.<DocOpComponent>create());
}
@Override
public Insert createInsert(String text) {
return (Insert) InsertImpl.make().setText(text).setType(INSERT);
}
@Override
public Retain createRetain(int count, boolean hasTrailingNewline) {
return (Retain) RetainImpl.make().setCount(count).setHasTrailingNewline(hasTrailingNewline)
.setType(RETAIN);
}
@Override
public RetainLine createRetainLine(int lineCount) {
return (RetainLine) RetainLineImpl.make().setLineCount(lineCount).setType(RETAIN_LINE);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/dto/client/DtoClientImpls.java | client/src/main/java/com/google/collide/dto/client/DtoClientImpls.java | // GENERATED SOURCE. DO NOT EDIT.
package com.google.collide.dto.client;
@SuppressWarnings({"cast"})
public class DtoClientImpls {
private DtoClientImpls() {}
public static final String CLIENT_SERVER_PROTOCOL_HASH = "33a27a91649a05ca880aa1d86554d053a6752e9c";
public static class AddMembersResponseImpl extends com.google.collide.dtogen.client.RoutableDtoClientImpl implements com.google.collide.dto.AddMembersResponse {
protected AddMembersResponseImpl() {}
@Override
public final native com.google.collide.json.shared.JsonArray<java.lang.String> getInvalidEmails() /*-{
return this["invalidEmails"];
}-*/;
public final native AddMembersResponseImpl setInvalidEmails(com.google.collide.json.client.JsoArray<java.lang.String> invalidEmails) /*-{
this["invalidEmails"] = invalidEmails;
return this;
}-*/;
public final native boolean hasInvalidEmails() /*-{
return this.hasOwnProperty("invalidEmails");
}-*/;
@Override
public final native com.google.collide.json.shared.JsonArray<com.google.collide.dto.UserDetailsWithRole> getNewMembers() /*-{
return this["newMembers"];
}-*/;
public final native AddMembersResponseImpl setNewMembers(com.google.collide.json.client.JsoArray<com.google.collide.dto.UserDetailsWithRole> newMembers) /*-{
this["newMembers"] = newMembers;
return this;
}-*/;
public final native boolean hasNewMembers() /*-{
return this.hasOwnProperty("newMembers");
}-*/;
}
public static class MockAddMembersResponseImpl extends AddMembersResponseImpl {
protected MockAddMembersResponseImpl() {}
public static native AddMembersResponseImpl make() /*-{
return {
_type: 1
};
}-*/; }
public static class AddProjectMembersImpl extends com.google.collide.dtogen.client.RoutableDtoClientImpl implements com.google.collide.dto.AddProjectMembers {
protected AddProjectMembersImpl() {}
@Override
public final native com.google.collide.dto.ChangeRoleInfo getChangeRoleInfo() /*-{
return this["changeRoleInfo"];
}-*/;
public final native AddProjectMembersImpl setChangeRoleInfo(com.google.collide.dto.ChangeRoleInfo changeRoleInfo) /*-{
this["changeRoleInfo"] = changeRoleInfo;
return this;
}-*/;
public final native boolean hasChangeRoleInfo() /*-{
return this.hasOwnProperty("changeRoleInfo");
}-*/;
@Override
public final native java.lang.String getUserEmails() /*-{
return this["userEmails"];
}-*/;
public final native AddProjectMembersImpl setUserEmails(java.lang.String userEmails) /*-{
this["userEmails"] = userEmails;
return this;
}-*/;
public final native boolean hasUserEmails() /*-{
return this.hasOwnProperty("userEmails");
}-*/;
@Override
public final native java.lang.String getProjectId() /*-{
return this["projectId"];
}-*/;
public final native AddProjectMembersImpl setProjectId(java.lang.String projectId) /*-{
this["projectId"] = projectId;
return this;
}-*/;
public final native boolean hasProjectId() /*-{
return this.hasOwnProperty("projectId");
}-*/;
public static native AddProjectMembersImpl make() /*-{
return {
_type: 2
};
}-*/; }
public static class AddWorkspaceMembersImpl extends com.google.collide.dtogen.client.RoutableDtoClientImpl implements com.google.collide.dto.AddWorkspaceMembers {
protected AddWorkspaceMembersImpl() {}
@Override
public final native java.lang.String getWorkspaceId() /*-{
return this["workspaceId"];
}-*/;
public final native AddWorkspaceMembersImpl setWorkspaceId(java.lang.String workspaceId) /*-{
this["workspaceId"] = workspaceId;
return this;
}-*/;
public final native boolean hasWorkspaceId() /*-{
return this.hasOwnProperty("workspaceId");
}-*/;
@Override
public final native com.google.collide.dto.ChangeRoleInfo getChangeRoleInfo() /*-{
return this["changeRoleInfo"];
}-*/;
public final native AddWorkspaceMembersImpl setChangeRoleInfo(com.google.collide.dto.ChangeRoleInfo changeRoleInfo) /*-{
this["changeRoleInfo"] = changeRoleInfo;
return this;
}-*/;
public final native boolean hasChangeRoleInfo() /*-{
return this.hasOwnProperty("changeRoleInfo");
}-*/;
@Override
public final native java.lang.String getUserEmails() /*-{
return this["userEmails"];
}-*/;
public final native AddWorkspaceMembersImpl setUserEmails(java.lang.String userEmails) /*-{
this["userEmails"] = userEmails;
return this;
}-*/;
public final native boolean hasUserEmails() /*-{
return this.hasOwnProperty("userEmails");
}-*/;
@Override
public final native java.lang.String getProjectId() /*-{
return this["projectId"];
}-*/;
public final native AddWorkspaceMembersImpl setProjectId(java.lang.String projectId) /*-{
this["projectId"] = projectId;
return this;
}-*/;
public final native boolean hasProjectId() /*-{
return this.hasOwnProperty("projectId");
}-*/;
public static native AddWorkspaceMembersImpl make() /*-{
return {
_type: 3
};
}-*/; }
public static class BeginUploadSessionImpl extends com.google.collide.dtogen.client.RoutableDtoClientImpl implements com.google.collide.dto.BeginUploadSession {
protected BeginUploadSessionImpl() {}
@Override
public final native java.lang.String getWorkspaceId() /*-{
return this["workspaceId"];
}-*/;
public final native BeginUploadSessionImpl setWorkspaceId(java.lang.String workspaceId) /*-{
this["workspaceId"] = workspaceId;
return this;
}-*/;
public final native boolean hasWorkspaceId() /*-{
return this.hasOwnProperty("workspaceId");
}-*/;
@Override
public final native com.google.collide.json.shared.JsonArray<java.lang.String> getWorkspacePathsToReplace() /*-{
return this["workspacePathsToReplace"];
}-*/;
public final native BeginUploadSessionImpl setWorkspacePathsToReplace(com.google.collide.json.client.JsoArray<java.lang.String> workspacePathsToReplace) /*-{
this["workspacePathsToReplace"] = workspacePathsToReplace;
return this;
}-*/;
public final native boolean hasWorkspacePathsToReplace() /*-{
return this.hasOwnProperty("workspacePathsToReplace");
}-*/;
@Override
public final native com.google.collide.json.shared.JsonArray<java.lang.String> getWorkspacePathsToUnzip() /*-{
return this["workspacePathsToUnzip"];
}-*/;
public final native BeginUploadSessionImpl setWorkspacePathsToUnzip(com.google.collide.json.client.JsoArray<java.lang.String> workspacePathsToUnzip) /*-{
this["workspacePathsToUnzip"] = workspacePathsToUnzip;
return this;
}-*/;
public final native boolean hasWorkspacePathsToUnzip() /*-{
return this.hasOwnProperty("workspacePathsToUnzip");
}-*/;
@Override
public final native com.google.collide.json.shared.JsonArray<java.lang.String> getWorkspaceDirsToCreate() /*-{
return this["workspaceDirsToCreate"];
}-*/;
public final native BeginUploadSessionImpl setWorkspaceDirsToCreate(com.google.collide.json.client.JsoArray<java.lang.String> workspaceDirsToCreate) /*-{
this["workspaceDirsToCreate"] = workspaceDirsToCreate;
return this;
}-*/;
public final native boolean hasWorkspaceDirsToCreate() /*-{
return this.hasOwnProperty("workspaceDirsToCreate");
}-*/;
@Override
public final native java.lang.String getClientId() /*-{
return this["clientId"];
}-*/;
public final native BeginUploadSessionImpl setClientId(java.lang.String clientId) /*-{
this["clientId"] = clientId;
return this;
}-*/;
public final native boolean hasClientId() /*-{
return this.hasOwnProperty("clientId");
}-*/;
@Override
public final native java.lang.String getSessionId() /*-{
return this["sessionId"];
}-*/;
public final native BeginUploadSessionImpl setSessionId(java.lang.String sessionId) /*-{
this["sessionId"] = sessionId;
return this;
}-*/;
public final native boolean hasSessionId() /*-{
return this.hasOwnProperty("sessionId");
}-*/;
public static native BeginUploadSessionImpl make() /*-{
return {
_type: 4
};
}-*/; }
public static class ChangeRoleInfoImpl extends com.google.collide.dtogen.client.RoutableDtoClientImpl implements com.google.collide.dto.ChangeRoleInfo {
protected ChangeRoleInfoImpl() {}
@Override
public final native com.google.collide.dto.Role getRole() /*-{
return this["role"]? @com.google.collide.dto.Role::valueOf(Ljava/lang/String;)(this["role"]): null;
}-*/;
public final native ChangeRoleInfoImpl setRole(com.google.collide.dto.Role role) /*-{
role = role.@com.google.collide.dto.Role::toString()();
this["role"] = role;
return this;
}-*/;
public final native boolean hasRole() /*-{
return this.hasOwnProperty("role");
}-*/;
@Override
public final native boolean emailSelf() /*-{
return this["emailSelf"];
}-*/;
public final native ChangeRoleInfoImpl setEmailSelf(boolean emailSelf) /*-{
this["emailSelf"] = emailSelf;
return this;
}-*/;
public final native boolean hasEmailSelf() /*-{
return this.hasOwnProperty("emailSelf");
}-*/;
@Override
public final native boolean emailUsers() /*-{
return this["emailUsers"];
}-*/;
public final native ChangeRoleInfoImpl setEmailUsers(boolean emailUsers) /*-{
this["emailUsers"] = emailUsers;
return this;
}-*/;
public final native boolean hasEmailUsers() /*-{
return this.hasOwnProperty("emailUsers");
}-*/;
@Override
public final native java.lang.String getEmailMessage() /*-{
return this["emailMessage"];
}-*/;
public final native ChangeRoleInfoImpl setEmailMessage(java.lang.String emailMessage) /*-{
this["emailMessage"] = emailMessage;
return this;
}-*/;
public final native boolean hasEmailMessage() /*-{
return this.hasOwnProperty("emailMessage");
}-*/;
public static native ChangeRoleInfoImpl make() /*-{
return {
_type: 5
};
}-*/; }
public static class ClientToServerDocOpImpl extends com.google.collide.dtogen.client.RoutableDtoClientImpl implements com.google.collide.dto.ClientToServerDocOp {
protected ClientToServerDocOpImpl() {}
@Override
public final native java.lang.String getWorkspaceId() /*-{
return this["workspaceId"];
}-*/;
public final native ClientToServerDocOpImpl setWorkspaceId(java.lang.String workspaceId) /*-{
this["workspaceId"] = workspaceId;
return this;
}-*/;
public final native boolean hasWorkspaceId() /*-{
return this.hasOwnProperty("workspaceId");
}-*/;
@Override
public final native java.lang.String getFileEditSessionKey() /*-{
return this["fileEditSessionKey"];
}-*/;
public final native ClientToServerDocOpImpl setFileEditSessionKey(java.lang.String fileEditSessionKey) /*-{
this["fileEditSessionKey"] = fileEditSessionKey;
return this;
}-*/;
public final native boolean hasFileEditSessionKey() /*-{
return this.hasOwnProperty("fileEditSessionKey");
}-*/;
@Override
public final native com.google.collide.dto.DocumentSelection getSelection() /*-{
return this["selection"];
}-*/;
public final native ClientToServerDocOpImpl setSelection(com.google.collide.dto.DocumentSelection selection) /*-{
this["selection"] = selection;
return this;
}-*/;
public final native boolean hasSelection() /*-{
return this.hasOwnProperty("selection");
}-*/;
@Override
public final native com.google.collide.json.shared.JsonArray<java.lang.String> getDocOps2() /*-{
return this["docOps2"];
}-*/;
public final native ClientToServerDocOpImpl setDocOps2(com.google.collide.json.client.JsoArray<java.lang.String> docOps2) /*-{
this["docOps2"] = docOps2;
return this;
}-*/;
public final native boolean hasDocOps2() /*-{
return this.hasOwnProperty("docOps2");
}-*/;
@Override
public final native int getCcRevision() /*-{
return this["ccRevision"];
}-*/;
public final native ClientToServerDocOpImpl setCcRevision(int ccRevision) /*-{
this["ccRevision"] = ccRevision;
return this;
}-*/;
public final native boolean hasCcRevision() /*-{
return this.hasOwnProperty("ccRevision");
}-*/;
@Override
public final native java.lang.String getClientId() /*-{
return this["clientId"];
}-*/;
public final native ClientToServerDocOpImpl setClientId(java.lang.String clientId) /*-{
this["clientId"] = clientId;
return this;
}-*/;
public final native boolean hasClientId() /*-{
return this.hasOwnProperty("clientId");
}-*/;
public static native ClientToServerDocOpImpl make() /*-{
return {
_type: 6
};
}-*/; }
public static class CodeBlockImpl extends com.google.collide.dtogen.client.RoutableDtoClientImpl implements com.google.collide.dto.CodeBlock {
protected CodeBlockImpl() {}
@Override
public final native java.lang.String getId() /*-{
return this[0];
}-*/;
public final native CodeBlockImpl setId(java.lang.String id) /*-{
this[0] = id;
return this;
}-*/;
public final native boolean hasId() /*-{
return this.hasOwnProperty(0);
}-*/;
@Override
public final native int getBlockType() /*-{
return this[1];
}-*/;
public final native CodeBlockImpl setBlockType(int blockType) /*-{
this[1] = blockType;
return this;
}-*/;
public final native boolean hasBlockType() /*-{
return this.hasOwnProperty(1);
}-*/;
@Override
public final native int getEndColumn() /*-{
return this[2];
}-*/;
public final native CodeBlockImpl setEndColumn(int endColumn) /*-{
this[2] = endColumn;
return this;
}-*/;
public final native boolean hasEndColumn() /*-{
return this.hasOwnProperty(2);
}-*/;
@Override
public final native int getEndLineNumber() /*-{
return this[3];
}-*/;
public final native CodeBlockImpl setEndLineNumber(int endLineNumber) /*-{
this[3] = endLineNumber;
return this;
}-*/;
public final native boolean hasEndLineNumber() /*-{
return this.hasOwnProperty(3);
}-*/;
@Override
public final native java.lang.String getName() /*-{
return this[4];
}-*/;
public final native CodeBlockImpl setName(java.lang.String name) /*-{
this[4] = name;
return this;
}-*/;
public final native boolean hasName() /*-{
return this.hasOwnProperty(4);
}-*/;
@Override
public final native int getStartColumn() /*-{
return this[5];
}-*/;
public final native CodeBlockImpl setStartColumn(int startColumn) /*-{
this[5] = startColumn;
return this;
}-*/;
public final native boolean hasStartColumn() /*-{
return this.hasOwnProperty(5);
}-*/;
@Override
public final native int getStartLineNumber() /*-{
return this[6];
}-*/;
public final native CodeBlockImpl setStartLineNumber(int startLineNumber) /*-{
this[6] = startLineNumber;
return this;
}-*/;
public final native boolean hasStartLineNumber() /*-{
return this.hasOwnProperty(6);
}-*/;
@Override
public final native com.google.collide.json.shared.JsonArray<com.google.collide.dto.CodeBlock> getChildren() /*-{
if (!this.hasOwnProperty(7)) {
this[7] = [];
}
return this[7];
}-*/;
public final native CodeBlockImpl setChildren(com.google.collide.json.client.JsoArray<com.google.collide.dto.CodeBlock> children) /*-{
this[7] = children;
return this;
}-*/;
public final native boolean hasChildren() /*-{
return this.hasOwnProperty(7);
}-*/;
}
public static class MockCodeBlockImpl extends CodeBlockImpl {
protected MockCodeBlockImpl() {}
public static native CodeBlockImpl make() /*-{
return [];
}-*/; }
public static class CodeBlockAssociationImpl extends com.google.collide.dtogen.client.RoutableDtoClientImpl implements com.google.collide.dto.CodeBlockAssociation {
protected CodeBlockAssociationImpl() {}
@Override
public final native java.lang.String getSourceFileId() /*-{
return this[0];
}-*/;
public final native CodeBlockAssociationImpl setSourceFileId(java.lang.String sourceFileId) /*-{
this[0] = sourceFileId;
return this;
}-*/;
public final native boolean hasSourceFileId() /*-{
return this.hasOwnProperty(0);
}-*/;
@Override
public final native java.lang.String getSourceLocalId() /*-{
return this[1];
}-*/;
public final native CodeBlockAssociationImpl setSourceLocalId(java.lang.String sourceLocalId) /*-{
this[1] = sourceLocalId;
return this;
}-*/;
public final native boolean hasSourceLocalId() /*-{
return this.hasOwnProperty(1);
}-*/;
@Override
public final native java.lang.String getTargetFileId() /*-{
return this[2];
}-*/;
public final native CodeBlockAssociationImpl setTargetFileId(java.lang.String targetFileId) /*-{
this[2] = targetFileId;
return this;
}-*/;
public final native boolean hasTargetFileId() /*-{
return this.hasOwnProperty(2);
}-*/;
@Override
public final native java.lang.String getTargetLocalId() /*-{
return this[3];
}-*/;
public final native CodeBlockAssociationImpl setTargetLocalId(java.lang.String targetLocalId) /*-{
this[3] = targetLocalId;
return this;
}-*/;
public final native boolean hasTargetLocalId() /*-{
return this.hasOwnProperty(3);
}-*/;
@Override
public final native boolean getIsRootAssociation() /*-{
return this[4];
}-*/;
public final native CodeBlockAssociationImpl setIsRootAssociation(boolean isRootAssociation) /*-{
this[4] = isRootAssociation;
return this;
}-*/;
public final native boolean hasIsRootAssociation() /*-{
return this.hasOwnProperty(4);
}-*/;
}
public static class MockCodeBlockAssociationImpl extends CodeBlockAssociationImpl {
protected MockCodeBlockAssociationImpl() {}
public static native CodeBlockAssociationImpl make() /*-{
return [];
}-*/; }
public static class CodeErrorImpl extends com.google.collide.json.client.Jso implements com.google.collide.dto.CodeError {
protected CodeErrorImpl() {}
@Override
public final native com.google.collide.dto.FilePosition getErrorEnd() /*-{
return this["errorEnd"];
}-*/;
public final native CodeErrorImpl setErrorEnd(com.google.collide.dto.FilePosition errorEnd) /*-{
this["errorEnd"] = errorEnd;
return this;
}-*/;
public final native boolean hasErrorEnd() /*-{
return this.hasOwnProperty("errorEnd");
}-*/;
@Override
public final native com.google.collide.dto.FilePosition getErrorStart() /*-{
return this["errorStart"];
}-*/;
public final native CodeErrorImpl setErrorStart(com.google.collide.dto.FilePosition errorStart) /*-{
this["errorStart"] = errorStart;
return this;
}-*/;
public final native boolean hasErrorStart() /*-{
return this.hasOwnProperty("errorStart");
}-*/;
@Override
public final native java.lang.String getMessage() /*-{
return this["message"];
}-*/;
public final native CodeErrorImpl setMessage(java.lang.String message) /*-{
this["message"] = message;
return this;
}-*/;
public final native boolean hasMessage() /*-{
return this.hasOwnProperty("message");
}-*/;
public static native CodeErrorImpl make() /*-{
return {
};
}-*/; }
public static class CodeErrorsImpl extends com.google.collide.dtogen.client.RoutableDtoClientImpl implements com.google.collide.dto.CodeErrors {
protected CodeErrorsImpl() {}
@Override
public final native java.lang.String getFileEditSessionKey() /*-{
return this["fileEditSessionKey"];
}-*/;
public final native CodeErrorsImpl setFileEditSessionKey(java.lang.String fileEditSessionKey) /*-{
this["fileEditSessionKey"] = fileEditSessionKey;
return this;
}-*/;
public final native boolean hasFileEditSessionKey() /*-{
return this.hasOwnProperty("fileEditSessionKey");
}-*/;
@Override
public final native com.google.collide.json.shared.JsonArray<com.google.collide.dto.CodeError> getCodeErrors() /*-{
return this["codeErrors"];
}-*/;
public final native CodeErrorsImpl setCodeErrors(com.google.collide.json.client.JsoArray<com.google.collide.dto.CodeError> codeErrors) /*-{
this["codeErrors"] = codeErrors;
return this;
}-*/;
public final native boolean hasCodeErrors() /*-{
return this.hasOwnProperty("codeErrors");
}-*/;
}
public static class MockCodeErrorsImpl extends CodeErrorsImpl {
protected MockCodeErrorsImpl() {}
public static native CodeErrorsImpl make() /*-{
return {
_type: 9
};
}-*/; }
public static class CodeErrorsRequestImpl extends com.google.collide.dtogen.client.RoutableDtoClientImpl implements com.google.collide.dto.CodeErrorsRequest {
protected CodeErrorsRequestImpl() {}
@Override
public final native java.lang.String getWorkspaceId() /*-{
return this["workspaceId"];
}-*/;
public final native CodeErrorsRequestImpl setWorkspaceId(java.lang.String workspaceId) /*-{
this["workspaceId"] = workspaceId;
return this;
}-*/;
public final native boolean hasWorkspaceId() /*-{
return this.hasOwnProperty("workspaceId");
}-*/;
@Override
public final native java.lang.String getFileEditSessionKey() /*-{
return this["fileEditSessionKey"];
}-*/;
public final native CodeErrorsRequestImpl setFileEditSessionKey(java.lang.String fileEditSessionKey) /*-{
this["fileEditSessionKey"] = fileEditSessionKey;
return this;
}-*/;
public final native boolean hasFileEditSessionKey() /*-{
return this.hasOwnProperty("fileEditSessionKey");
}-*/;
public static native CodeErrorsRequestImpl make() /*-{
return {
_type: 10
};
}-*/; }
public static class CodeGraphImpl extends com.google.collide.json.client.Jso implements com.google.collide.dto.CodeGraph {
protected CodeGraphImpl() {}
@Override
public final native com.google.collide.json.shared.JsonArray<com.google.collide.dto.TypeAssociation> getTypeAssociations() /*-{
return this["typeAssociations"];
}-*/;
public final native CodeGraphImpl setTypeAssociations(com.google.collide.json.client.JsoArray<com.google.collide.dto.TypeAssociation> typeAssociations) /*-{
this["typeAssociations"] = typeAssociations;
return this;
}-*/;
public final native boolean hasTypeAssociations() /*-{
return this.hasOwnProperty("typeAssociations");
}-*/;
@Override
public final native com.google.collide.json.shared.JsonArray<com.google.collide.dto.ImportAssociation> getImportAssociations() /*-{
return this["importAssociations"];
}-*/;
public final native CodeGraphImpl setImportAssociations(com.google.collide.json.client.JsoArray<com.google.collide.dto.ImportAssociation> importAssociations) /*-{
this["importAssociations"] = importAssociations;
return this;
}-*/;
public final native boolean hasImportAssociations() /*-{
return this.hasOwnProperty("importAssociations");
}-*/;
@Override
public final native com.google.collide.json.shared.JsonStringMap<com.google.collide.dto.CodeBlock> getCodeBlockMap() /*-{
return this["codeBlockMap"];
}-*/;
public final native CodeGraphImpl setCodeBlockMap(com.google.collide.json.client.JsoStringMap<com.google.collide.dto.CodeBlock> codeBlockMap) /*-{
this["codeBlockMap"] = codeBlockMap;
return this;
}-*/;
public final native boolean hasCodeBlockMap() /*-{
return this.hasOwnProperty("codeBlockMap");
}-*/;
@Override
public final native com.google.collide.dto.CodeBlock getDefaultPackage() /*-{
return this["defaultPackage"];
}-*/;
public final native CodeGraphImpl setDefaultPackage(com.google.collide.dto.CodeBlock defaultPackage) /*-{
this["defaultPackage"] = defaultPackage;
return this;
}-*/;
public final native boolean hasDefaultPackage() /*-{
return this.hasOwnProperty("defaultPackage");
}-*/;
@Override
public final native com.google.collide.json.shared.JsonArray<com.google.collide.dto.InheritanceAssociation> getInheritanceAssociations() /*-{
return this["inheritanceAssociations"];
}-*/;
public final native CodeGraphImpl setInheritanceAssociations(com.google.collide.json.client.JsoArray<com.google.collide.dto.InheritanceAssociation> inheritanceAssociations) /*-{
this["inheritanceAssociations"] = inheritanceAssociations;
return this;
}-*/;
public final native boolean hasInheritanceAssociations() /*-{
return this.hasOwnProperty("inheritanceAssociations");
}-*/;
public static native CodeGraphImpl make() /*-{
return {
};
}-*/; }
public static class CodeGraphFreshnessImpl extends com.google.collide.json.client.Jso implements com.google.collide.dto.CodeGraphFreshness {
protected CodeGraphFreshnessImpl() {}
@Override
public final native java.lang.String getWorkspaceLinks() /*-{
return this["workspaceLinks"];
}-*/;
public final native CodeGraphFreshnessImpl setWorkspaceLinks(java.lang.String workspaceLinks) /*-{
this["workspaceLinks"] = workspaceLinks;
return this;
}-*/;
public final native boolean hasWorkspaceLinks() /*-{
return this.hasOwnProperty("workspaceLinks");
}-*/;
@Override
public final native java.lang.String getWorkspaceTree() /*-{
return this["workspaceTree"];
}-*/;
public final native CodeGraphFreshnessImpl setWorkspaceTree(java.lang.String workspaceTree) /*-{
this["workspaceTree"] = workspaceTree;
return this;
}-*/;
public final native boolean hasWorkspaceTree() /*-{
return this.hasOwnProperty("workspaceTree");
}-*/;
@Override
public final native java.lang.String getFileTree() /*-{
return this["fileTree"];
}-*/;
public final native CodeGraphFreshnessImpl setFileTree(java.lang.String fileTree) /*-{
this["fileTree"] = fileTree;
return this;
}-*/;
public final native boolean hasFileTree() /*-{
return this.hasOwnProperty("fileTree");
}-*/;
@Override
public final native java.lang.String getLibsSubgraph() /*-{
return this["libsSubgraph"];
}-*/;
public final native CodeGraphFreshnessImpl setLibsSubgraph(java.lang.String libsSubgraph) /*-{
this["libsSubgraph"] = libsSubgraph;
return this;
}-*/;
public final native boolean hasLibsSubgraph() /*-{
return this.hasOwnProperty("libsSubgraph");
}-*/;
@Override
public final native java.lang.String getFileReferences() /*-{
return this["fileReferences"];
}-*/;
public final native CodeGraphFreshnessImpl setFileReferences(java.lang.String fileReferences) /*-{
this["fileReferences"] = fileReferences;
return this;
}-*/;
public final native boolean hasFileReferences() /*-{
return this.hasOwnProperty("fileReferences");
}-*/;
@Override
public final native java.lang.String getFullGraph() /*-{
return this["fullGraph"];
}-*/;
public final native CodeGraphFreshnessImpl setFullGraph(java.lang.String fullGraph) /*-{
this["fullGraph"] = fullGraph;
return this;
}-*/;
public final native boolean hasFullGraph() /*-{
return this.hasOwnProperty("fullGraph");
}-*/;
@Override
public final native java.lang.String getFileTreeHash() /*-{
return this["fileTreeHash"];
}-*/;
public final native CodeGraphFreshnessImpl setFileTreeHash(java.lang.String fileTreeHash) /*-{
this["fileTreeHash"] = fileTreeHash;
return this;
}-*/;
public final native boolean hasFileTreeHash() /*-{
return this.hasOwnProperty("fileTreeHash");
}-*/;
public static native CodeGraphFreshnessImpl make() /*-{
return {
};
}-*/; }
public static class CodeGraphRequestImpl extends com.google.collide.dtogen.client.RoutableDtoClientImpl implements com.google.collide.dto.CodeGraphRequest {
protected CodeGraphRequestImpl() {}
@Override
public final native java.lang.String getWorkspaceId() /*-{
return this["workspaceId"];
}-*/;
public final native CodeGraphRequestImpl setWorkspaceId(java.lang.String workspaceId) /*-{
this["workspaceId"] = workspaceId;
return this;
}-*/;
public final native boolean hasWorkspaceId() /*-{
return this.hasOwnProperty("workspaceId");
}-*/;
@Override
public final native com.google.collide.dto.CodeGraphFreshness getFreshness() /*-{
return this["freshness"];
}-*/;
public final native CodeGraphRequestImpl setFreshness(com.google.collide.dto.CodeGraphFreshness freshness) /*-{
this["freshness"] = freshness;
return this;
}-*/;
public final native boolean hasFreshness() /*-{
return this.hasOwnProperty("freshness");
}-*/;
@Override
public final native java.lang.String getFilePath() /*-{
return this["filePath"];
}-*/;
public final native CodeGraphRequestImpl setFilePath(java.lang.String filePath) /*-{
this["filePath"] = filePath;
return this;
}-*/;
public final native boolean hasFilePath() /*-{
return this.hasOwnProperty("filePath");
}-*/;
public static native CodeGraphRequestImpl make() /*-{
return {
_type: 11
};
}-*/; }
public static class CodeGraphResponseImpl extends com.google.collide.dtogen.client.RoutableDtoClientImpl implements com.google.collide.dto.CodeGraphResponse {
protected CodeGraphResponseImpl() {}
@Override
public final native com.google.collide.dto.CodeGraphFreshness getFreshness() /*-{
return this["freshness"];
}-*/;
public final native CodeGraphResponseImpl setFreshness(com.google.collide.dto.CodeGraphFreshness freshness) /*-{
this["freshness"] = freshness;
return this;
}-*/;
public final native boolean hasFreshness() /*-{
return this.hasOwnProperty("freshness");
}-*/;
@Override
public final native java.lang.String getWorkspaceTreeJson() /*-{
return this["workspaceTreeJson"];
}-*/;
public final native CodeGraphResponseImpl setWorkspaceTreeJson(java.lang.String workspaceTreeJson) /*-{
this["workspaceTreeJson"] = workspaceTreeJson;
return this;
}-*/;
public final native boolean hasWorkspaceTreeJson() /*-{
return this.hasOwnProperty("workspaceTreeJson");
}-*/;
@Override
public final native java.lang.String getLibsSubgraphJson() /*-{
return this["libsSubgraphJson"];
}-*/;
public final native CodeGraphResponseImpl setLibsSubgraphJson(java.lang.String libsSubgraphJson) /*-{
this["libsSubgraphJson"] = libsSubgraphJson;
return this;
}-*/;
public final native boolean hasLibsSubgraphJson() /*-{
return this.hasOwnProperty("libsSubgraphJson");
}-*/;
@Override
public final native java.lang.String getFullGraphJson() /*-{
return this["fullGraphJson"];
}-*/;
public final native CodeGraphResponseImpl setFullGraphJson(java.lang.String fullGraphJson) /*-{
this["fullGraphJson"] = fullGraphJson;
return this;
}-*/;
public final native boolean hasFullGraphJson() /*-{
return this.hasOwnProperty("fullGraphJson");
}-*/;
@Override
public final native java.lang.String getFileTreeJson() /*-{
return this["fileTreeJson"];
}-*/;
public final native CodeGraphResponseImpl setFileTreeJson(java.lang.String fileTreeJson) /*-{
this["fileTreeJson"] = fileTreeJson;
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | true |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/clientlibs/vertx/VertxBus.java | client/src/main/java/com/google/collide/clientlibs/vertx/VertxBus.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.clientlibs.vertx;
import com.google.gwt.core.client.JavaScriptObject;
/**
* An interface exposing the operations which can be performed over the vertx event bus.
*/
public interface VertxBus {
/**
* Handler for receiving replies to messages you sent on the event bus.
*/
public interface ReplyHandler {
void onReply(String message);
}
/**
* Client for sending a reply in response to a message you received on the event bus.
*/
public static class ReplySender extends JavaScriptObject {
protected ReplySender() {
}
public final native void sendReply(String message) /*-{
this(message);
}-*/;
}
/**
* Handler messages sent to you on the event bus.
*/
public interface MessageHandler {
void onMessage(String message, ReplySender replySender);
}
public interface ConnectionListener {
void onOpen();
void onClose();
}
public static final short CONNECTING = 0;
public static final short OPEN = 1;
public static final short CLOSING = 2;
public static final short CLOSED = 3;
/**
* Sets a callback which is called when the eventbus is open. The eventbus is opened automatically
* upon instantiation so this should be the first thing that is set after instantiation.
*/
public void setOnOpenCallback(ConnectionListener callback);
/** Sets a callback which is called when the eventbus is closed */
public void setOnCloseCallback(ConnectionListener callback);
/**
* Sends a message to an address, providing an replyHandler.
*/
public void send(String address, String message, ReplyHandler replyHandler);
/**
* Sends a message to an address.
*/
public void send(String address, String message);
/** Closes the event bus */
public void close();
/**
* @return the ready state of the event bus
*/
public short getReadyState();
/**
* Registers a new handler which will listener for messages sent to the specified address.
*/
public void register(String address, MessageHandler handler);
/**
* Unregistered a previously registered handler listening on the specified address.
*/
public void unregister(String address, MessageHandler handler);
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/clientlibs/vertx/VertxBusImpl.java | client/src/main/java/com/google/collide/clientlibs/vertx/VertxBusImpl.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.clientlibs.vertx;
import com.google.gwt.core.client.JavaScriptObject;
/**
* A GWT overlay object for the Vertx Event Bus.
*/
public class VertxBusImpl extends JavaScriptObject implements VertxBus {
public static final native VertxBus create() /*-{
if (!$wnd.collide) $wnd.collide = {};
var protocol = $wnd.collide.protocol || window.location.protocol;
var hostname = $wnd.collide.host || window.location.hostname;
var port = $wnd.collide.port || window.location.port;
var path;
if ($wnd.collide.path) {
path = $wnd.collide.path;
} else {
path = window.location.pathname;
path = path.indexOf('/collide')==-1 ?
'/' : '/collide/';
}
var url = protocol + '//' + hostname;
if (port) url += ':' + port;
url += path + "eventbus";
return new $wnd.vertx.EventBus(url);
}-*/;
protected VertxBusImpl() {}
@Override
public final native void setOnOpenCallback(ConnectionListener callback) /*-{
this.onopen = function() {
callback.@com.google.collide.clientlibs.vertx.VertxBus.ConnectionListener::onOpen()();
}
}-*/;
@Override
public final native void setOnCloseCallback(ConnectionListener callback) /*-{
this.onclose = function() {
callback.@com.google.collide.clientlibs.vertx.VertxBus.ConnectionListener::onClose()();
}
}-*/;
@Override
public final void send(String address, String message) {
send(address, message, null);
}
@Override
public final native void send(String address, String message, ReplyHandler replyHandler) /*-{
var replyHandlerWrapper;
if(replyHandler) {
replyHandlerWrapper = function(reply) {
if (reply) {
replyHandler.@com.google.collide.clientlibs.vertx.VertxBus.ReplyHandler::onReply(Ljava/lang/String;)(reply.dto)
} else {
console.trace("Received null reply from ", address, " sent message: ", message);
}
}
}
this.send(address, {dto: message}, replyHandlerWrapper);
}-*/;
@Override
public final native void close() /*-{
this.close();
}-*/;
@Override
public final native short getReadyState() /*-{
return this.readyState();
}-*/;
@Override
public final native void register(String address, MessageHandler handler) /*-{
var handlerWrapper = function(message, replier) {
handler.@com.google.collide.clientlibs.vertx.VertxBus.MessageHandler::onMessage(Ljava/lang/String;Lcom/google/collide/clientlibs/vertx/VertxBus$ReplySender;)
(message.dto, replier)
}
// Ghetto!
handler.__unregisterRef = handlerWrapper;
this.registerHandler(address, handlerWrapper);
}-*/;
@Override
public final native void unregister(String address, MessageHandler handler) /*-{
this.unregisterHandler(address, handler.__unregisterRef);
}-*/;
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/clientlibs/model/Workspace.java | client/src/main/java/com/google/collide/clientlibs/model/Workspace.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.clientlibs.model;
import com.google.collide.dto.GetWorkspaceMetaDataResponse;
/**
* A workspace.
*/
public interface Workspace {
String getOwningProjectId();
GetWorkspaceMetaDataResponse getWorkspaceMetaData();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/clientlibs/model/ProjectTemplate.java | client/src/main/java/com/google/collide/clientlibs/model/ProjectTemplate.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.clientlibs.model;
/**
* An object which encapsulates a ProjectTemplate from the server.
*/
/*
* This is located within WorkspaceManager since this operates at the workspace level not the
* Project level (contrary to its name). A template is loaded into a branch via a call to
* loadTemplate.
*/
public class ProjectTemplate {
public static ProjectTemplate create(String templateName, String templateTag) {
return new ProjectTemplate(templateName, templateTag, templateName);
}
public final String name;
public final String id;
public final String description;
private ProjectTemplate(String name, String id, String description) {
this.name = name;
this.id = id;
this.description = description;
}
} | java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/clientlibs/invalidation/DropRecoveringInvalidationControllerFactory.java | client/src/main/java/com/google/collide/clientlibs/invalidation/DropRecoveringInvalidationControllerFactory.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.clientlibs.invalidation;
import com.google.collide.clientlibs.invalidation.InvalidationManager.Recoverer;
import com.google.collide.shared.invalidations.InvalidationObjectId;
import com.google.collide.shared.util.Timer;
import com.google.collide.shared.util.Timer.Factory;
/**
* A factory which can return a {@link DropRecoveringInvalidationController}. Helps to dodge some
* GWT.create dependency stuff from TangoLogger.
*
*/
class DropRecoveringInvalidationControllerFactory {
public final InvalidationLogger logger;
private final Factory timerFactory;
public DropRecoveringInvalidationControllerFactory(
InvalidationLogger logger, Timer.Factory timerFactory) {
this.logger = logger;
this.timerFactory = timerFactory;
}
public DropRecoveringInvalidationController create(InvalidationObjectId<?> objectId,
InvalidationRegistrar.Listener listener, Recoverer recoverer) {
return new DropRecoveringInvalidationController(
logger, objectId, listener, recoverer, timerFactory);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/clientlibs/invalidation/InvalidationLogger.java | client/src/main/java/com/google/collide/clientlibs/invalidation/InvalidationLogger.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.clientlibs.invalidation;
import java.util.logging.Level;
import com.google.collide.shared.util.SharedLogUtils;
import com.google.collide.shared.util.StringUtils;
import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;
import com.google.gwt.user.client.Window;
/**
* An implementation of the {@link Logger} used by the SimpleListener.
*/
public class InvalidationLogger {
public static InvalidationLogger create() {
String value = Window.Location.getParameter("tangoLogging");
if (StringUtils.isNullOrEmpty(value) || value.equalsIgnoreCase("false")) {
return new InvalidationLogger(false, false);
} else if (value.equalsIgnoreCase("fine")) {
return new InvalidationLogger(true, true);
} else {
return new InvalidationLogger(true, false);
}
}
private final boolean enabled;
private final boolean logFine;
public InvalidationLogger(boolean enabled, boolean logFine) {
this.enabled = enabled;
this.logFine = logFine;
}
public void fine(String template, Object... args) {
if (enabled && logFine) {
SharedLogUtils.info(getClass(), format(template, args));
}
}
public void info(String template, Object... args) {
if (enabled) {
SharedLogUtils.info(getClass(), format(template, args));
}
}
public boolean isLoggable(Level level) {
return enabled;
}
public void log(Level level, String template, Object... args) {
if (enabled) {
SharedLogUtils.info(getClass(), format(template, args));
}
}
public void severe(String template, Object... args) {
if (enabled) {
SharedLogUtils.error(getClass(), format(template, args));
}
}
public void warning(String template, Object... args) {
if (enabled) {
SharedLogUtils.warn(getClass(), format(template, args));
}
}
/** A helper object which simplifies formatting */
private static class ArgumentFormatHelper {
private final Object[] args;
private int current = 0;
public ArgumentFormatHelper(Object... args) {
this.args = args;
}
public String next() {
if (args == null || current >= args.length) {
return "[MISSING ARG]";
}
return args[current++].toString();
}
public String rest() {
if (args == null || current >= args.length) {
return "";
}
StringBuilder builder = new StringBuilder();
for (int i = current; i < args.length; i++) {
builder.append(" [").append(args[i].toString()).append(']');
}
return builder.toString();
}
}
/**
* GWT does not emulate string formatting so we just do a simple stupid one which looks for %s or
* %d and replaces it with an arg. If there are less args than %markers we put in [MISSING ARG].
* If there are more args than %markers we just append them at the end within brackets.
*/
private static String format(String template, Object... args) {
StringBuilder builder = new StringBuilder();
ArgumentFormatHelper helper = new ArgumentFormatHelper(args);
RegExp formatMatcher = RegExp.compile("(%s)|(%d)", "ig");
int lastIndex = 0;
MatchResult result = formatMatcher.exec(template);
while (result != null) {
String fragment = template.substring(lastIndex, result.getIndex() - 1);
builder.append(fragment);
builder.append(helper.next());
lastIndex = result.getIndex() + result.getGroup(0).length();
}
String lastFragment = template.substring(lastIndex, template.length());
builder.append(lastFragment);
builder.append(helper.rest());
return builder.toString();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/clientlibs/invalidation/InvalidationRegistrar.java | client/src/main/java/com/google/collide/clientlibs/invalidation/InvalidationRegistrar.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.clientlibs.invalidation;
import javax.annotation.Nullable;
import com.google.collide.dto.client.DtoUtils;
import com.google.collide.dtogen.shared.ServerToClientDto;
import com.google.collide.shared.invalidations.InvalidationObjectId;
import com.google.collide.shared.util.ListenerRegistrar.Remover;
/**
* An object which can register and unregister for Tango invalidations.
*/
public interface InvalidationRegistrar {
/**
* A handle to the registration for invalidations.
*
* <p>
* Clients that registered with {@code recoverMissingPayloads=true} must call
* {@link #initializeRecoverer(long)} after receiving the initial object
* contents.
*
*/
public interface RemovableHandle extends Remover {
/**
* Sets the next expected version of the object.
*
* <p>
* This is required to bootstrap the ability to recover missing payloads or
* squelched invalidations.
*
* <p>
* This can be called multiple times to tell the tango recoverer that your
* model is now at a new version.
*/
void initializeRecoverer(long nextExpectedVersion);
}
/**
* A listener for Tango object invalidation.
*/
public interface Listener {
/**
* A handle to notify the caller of {@link Listener#onInvalidated} that
* this invalidation will be processed asychronously. This means the caller will not call again
* until the current invalidation has finished being processed.
*/
public interface AsyncProcessingHandle {
/**
* Notifies the caller that the invalidation will be processed asychronously.
*
* <p>
* {@link #finishedAsyncProcessing()} must be called when the invalidation has been processed.
*/
void startedAsyncProcessing();
/**
* Notifies the caller of {@link Listener#onInvalidated} that the
* invalidation has finished being processed.
*/
void finishedAsyncProcessing();
}
/**
* @param payload the invalidation payload, or null if no payload arrived
* @param asyncProcessingHandle for objects that require payload recovery, this will tell the
* recovery stack to allow for async processing of this payload
*/
void onInvalidated(String objectName, long version, @Nullable String payload,
AsyncProcessingHandle asyncProcessingHandle);
}
/**
* A listener which handles deserializing a Tango payload into a given DTO
* type.
*
* @param <T> the type of dto.
*/
public abstract static class DtoListener<T extends ServerToClientDto> implements Listener {
private final int routingType;
public DtoListener(int routingType) {
this.routingType = routingType;
}
@Override
public void onInvalidated(String objectName, long version, String payload,
AsyncProcessingHandle asyncProcessingHandle) {
T dto = null;
if (payload != null) {
dto = DtoUtils.parseAsDto(payload, routingType);
}
onInvalidatedDto(objectName, version, dto, asyncProcessingHandle);
}
/**
* @see Listener#onInvalidated
*/
public abstract void onInvalidatedDto(String objectName, long version, T dto,
AsyncProcessingHandle asyncProcessingHandle);
}
/**
* Registers the client to receive invalidations for the given object.
*
* <p>
* If the client requires recovering from missing payloads ({@code
* recoverMissingPayloads} is true), the suggested usage pattern is:
* <ul>
* <li>Register for Tango invalidations using this method</li>
* <li>Out-of-band (e.g. via XHR) fetch the initial contents of the object
* </li>
* <li>Call {@link RemovableHandle#initializeRecoverer} with the fetched
* object's version</li>
* </ul>
*/
public RemovableHandle register(InvalidationObjectId<?> objectId, Listener eventListener);
public void unregister(InvalidationObjectId<?> objectId);
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/clientlibs/invalidation/DropRecoveringInvalidationController.java | client/src/main/java/com/google/collide/clientlibs/invalidation/DropRecoveringInvalidationController.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.clientlibs.invalidation;
import com.google.collide.clientlibs.invalidation.InvalidationManager.Recoverer;
import com.google.collide.clientlibs.invalidation.InvalidationRegistrar.Listener;
import com.google.collide.clientlibs.invalidation.InvalidationRegistrar.Listener.AsyncProcessingHandle;
import com.google.collide.dto.RecoverFromDroppedTangoInvalidationResponse.RecoveredPayload;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.invalidations.InvalidationObjectId;
import com.google.collide.shared.invalidations.InvalidationUtils;
import com.google.collide.shared.util.JsonCollections;
import com.google.collide.shared.util.Reorderer;
import com.google.collide.shared.util.Reorderer.ItemSink;
import com.google.collide.shared.util.Reorderer.TimeoutCallback;
import com.google.collide.shared.util.Timer;
import com.google.collide.shared.util.Timer.Factory;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.user.client.Random;
/**
* A controller for ensuring all (even dropped payload) invalidations are given to the
* {@link Listener} in-order. This will queue out-of-order invalidations (if prior invalidations
* were dropped), perform out-of-band recovery, and replay invalidations in-order to the listener.
*
*/
class DropRecoveringInvalidationController {
private static final int ERROR_RETRY_DELAY_MS = 15000;
private final InvalidationLogger logger;
private final Factory timerFactory;
private final InvalidationObjectId<?> objectId;
private final Recoverer recoverer;
/** Reorderer of invalidations, storing the payload. */
private final Reorderer<String> invalidationReorderer;
private boolean isRecovering;
private class ReordererSink implements ItemSink<String> {
private final Listener listener;
private boolean isListenerProcessingAsync;
private final AsyncProcessingHandle asyncProcessingHandle = new AsyncProcessingHandle() {
@Override
public void startedAsyncProcessing() {
isListenerProcessingAsync = true;
}
@Override
public void finishedAsyncProcessing() {
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
isListenerProcessingAsync = false;
dispatchQueuedPayloads();
}
});
}
};
private final JsonArray<String> queuedPayloads = JsonCollections.createArray();
private int firstQueuedPayloadVersion;
ReordererSink(Listener listener) {
this.listener = listener;
}
@Override
public void onItem(String payload, int version) {
if (!isListenerProcessingAsync) {
listener.onInvalidated(objectId.getName(), version, payload, asyncProcessingHandle);
} else {
if (queuedPayloads.isEmpty()) {
firstQueuedPayloadVersion = version;
}
queuedPayloads.add(payload);
}
}
void handleSetNextExpectedVersion(int nextExpectedVersion) {
while (!queuedPayloads.isEmpty() && firstQueuedPayloadVersion < nextExpectedVersion) {
queuedPayloads.remove(0);
firstQueuedPayloadVersion++;
}
}
private void dispatchQueuedPayloads() {
while (!queuedPayloads.isEmpty() && !isListenerProcessingAsync) {
listener.onInvalidated(objectId.getName(), firstQueuedPayloadVersion++,
queuedPayloads.remove(0), asyncProcessingHandle);
}
}
}
private final ReordererSink reorderedItemSink;
private final TimeoutCallback outOfOrderCallback = new TimeoutCallback() {
@Override
public void onTimeout(int lastVersionDispatched) {
logger.fine(
"Entering recovery for object %s, last version %s, due to out-of-order.", objectId,
lastVersionDispatched);
recover();
}
};
DropRecoveringInvalidationController(InvalidationLogger logger, InvalidationObjectId<?> objectId,
InvalidationRegistrar.Listener listener, Recoverer recoverer,
Timer.Factory timerFactory) {
this.logger = logger;
this.objectId = objectId;
this.recoverer = recoverer;
this.timerFactory = timerFactory;
reorderedItemSink = new ReordererSink(listener);
/*
* We don't know the actual version to expect at this point, so we will just queue until our
* client calls through with a version to expect
*/
// TimeoutMs is very small since tango will not deliver out-of-order items.
invalidationReorderer =
Reorderer.create(0, reorderedItemSink, 1, outOfOrderCallback, timerFactory);
invalidationReorderer.queueUntilSkipToVersionIsCalled();
// Disable timeout until we know the next expected version
invalidationReorderer.setTimeoutEnabled(false);
}
void cleanup() {
invalidationReorderer.cleanup();
}
void setNextExpectedVersion(int nextExpectedVersion) {
reorderedItemSink.handleSetNextExpectedVersion(nextExpectedVersion);
invalidationReorderer.skipToVersion(nextExpectedVersion);
invalidationReorderer.setTimeoutEnabled(true);
}
/**
* @param version the version of the payload, or
* {@link InvalidationUtils#UNKNOWN_VERSION}
*/
void handleInvalidated(String payload, long version, boolean isEmptyPayload) {
if (version > Integer.MAX_VALUE) {
// 1 invalidation per sec would take 24k days to exhaust the positive integer range
throw new IllegalStateException("Version space exhausted (int on client)");
}
// Check if we dropped a payload or msised an invalidation
if (version == InvalidationUtils.UNKNOWN_VERSION || (payload == null && !isEmptyPayload)) {
logger.fine("Entering recovery due to unknown version or missing payload."
+ " Object id: %s, Version: %s, Payload(%s): %s", objectId, version, isEmptyPayload,
payload);
recover();
return;
}
invalidationReorderer.acceptItem(payload, (int) version);
}
void recover() {
if (isRecovering) {
return;
}
isRecovering = true;
int currentClientVersion = invalidationReorderer.getNextExpectedVersion() - 1;
// Disable timeout, as it would trigger a recover
invalidationReorderer.setTimeoutEnabled(false);
// Perform XHR, feed results into reorderer, get callbacks
recoverer.recoverPayloads(objectId, currentClientVersion, new Recoverer.Callback() {
@Override
public void onPayloadsRecovered(JsonArray<RecoveredPayload> payloads, int currentVersion) {
for (int i = 0; i < payloads.size(); i++) {
RecoveredPayload payload = payloads.get(i);
invalidationReorderer.acceptItem(payload.getPayload(), payload.getPayloadVersion());
}
invalidationReorderer.skipToVersion(currentVersion + 1);
isRecovering = false;
invalidationReorderer.setTimeoutEnabled(true);
}
@Override
public void onError() {
// Consider ourselves to be in the "retrying" state during this delay
timerFactory.createTimer(new Runnable() {
@Override
public void run() {
isRecovering = false;
// This will end up retrying
invalidationReorderer.setTimeoutEnabled(true);
}
}).schedule(ERROR_RETRY_DELAY_MS + Random.nextInt(ERROR_RETRY_DELAY_MS / 10));
}
});
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/clientlibs/invalidation/ScopedInvalidationRegistrar.java | client/src/main/java/com/google/collide/clientlibs/invalidation/ScopedInvalidationRegistrar.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.clientlibs.invalidation;
import com.google.collide.shared.invalidations.InvalidationObjectId;
import com.google.collide.shared.util.ListenerRegistrar.RemoverManager;
/**
* Handles registration of Tango objects and unregisters them when the object is cleaned up.
*/
public class ScopedInvalidationRegistrar implements InvalidationRegistrar {
private final InvalidationRegistrar registrar;
private final RemoverManager removerManager = new RemoverManager();
public ScopedInvalidationRegistrar(InvalidationRegistrar registrar) {
this.registrar = registrar;
}
@Override
public RemovableHandle register(
InvalidationObjectId<?> tangoObjectId, InvalidationRegistrar.Listener eventListener) {
RemovableHandle handle = registrar.register(tangoObjectId, eventListener);
removerManager.track(handle);
return handle;
}
public void cleanup() {
removerManager.remove();
}
@Override
public void unregister(InvalidationObjectId<?> objectId) {
registrar.unregister(objectId);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/clientlibs/invalidation/InvalidationManager.java | client/src/main/java/com/google/collide/clientlibs/invalidation/InvalidationManager.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.clientlibs.invalidation;
import javax.annotation.Nullable;
import com.google.collide.client.status.StatusManager;
import com.google.collide.client.util.ClientTimer;
import com.google.collide.dto.RecoverFromDroppedTangoInvalidationResponse.RecoveredPayload;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.shared.invalidations.InvalidationObjectId;
import com.google.collide.shared.invalidations.InvalidationObjectId.VersioningRequirement;
import com.google.collide.shared.invalidations.InvalidationUtils;
import com.google.collide.shared.util.JsonCollections;
import com.google.common.base.Preconditions;
/**
* A manager which is responsible for registering and unregistering objects with Tango and notifying
* the appropriate listener.
*
*/
public class InvalidationManager implements InvalidationRegistrar {
/**
* The version used when calling {@link InvalidationRegistrar.Listener#onInvalidated} when Tango
* reports that the invalidation's version was unknown.
*/
public static InvalidationManager create(StatusManager statusManager, Recoverer recoverer) {
return new InvalidationManager(recoverer, new DropRecoveringInvalidationControllerFactory(
logger, ClientTimer.FACTORY));
}
/**
* Allows for clients to recover from missing or squelched payloads.
*/
public interface Recoverer {
/**
* Called from {@link Recoverer#recoverPayloads(InvalidationObjectId, int, Callback)} with the
* response.
*/
public interface Callback {
void onPayloadsRecovered(JsonArray<RecoveredPayload> payloads, int currentObjectVersion);
void onError();
}
/**
* Called when a recovery is needed.
*
* @param objectId the ID of the object that needs to be recovered
* @param currentClientVersion the last version of the object that was delivered to the client
*/
void recoverPayloads(InvalidationObjectId<?> objectId, int currentClientVersion, Callback callback);
}
private static final InvalidationLogger logger = InvalidationLogger.create();
// Listener-scoped
/** Keyed by the object name */
private final JsonStringMap<InvalidationRegistrar.Listener> listenerMap =
JsonCollections.createMap();
/** Keyed by the object name */
private final JsonStringMap<DropRecoveringInvalidationController>
dropRecoveringInvalidationControllers = JsonCollections.createMap();
// Misc
private final Recoverer recoverer;
private final DropRecoveringInvalidationControllerFactory
dropRecoveringInvalidationControllerFactory;
private InvalidationManager(Recoverer recoverer,
DropRecoveringInvalidationControllerFactory dropRecoveringInvalidationControllerFactory) {
if (recoverer == null) {
recoverer = new Recoverer() {
@Override
public void recoverPayloads(
InvalidationObjectId<?> objectId, int currentClientVersion, Callback callback) {
// null operation
}
};
}
this.recoverer = recoverer;
this.dropRecoveringInvalidationControllerFactory = dropRecoveringInvalidationControllerFactory;
}
/**
* Registers a new listener for a specific object.
*/
@Override
public RemovableHandle register(final InvalidationObjectId<?> objectId, Listener eventListener) {
logger.fine("Registering object: %s", objectId);
final String objectName = objectId.getName();
listenerMap.put(objectName, eventListener);
final DropRecoveringInvalidationController dropRecoveringInvalidationController;
if (objectId.getVersioningRequirement() == VersioningRequirement.PAYLOADS) {
dropRecoveringInvalidationController =
dropRecoveringInvalidationControllerFactory.create(objectId, eventListener, recoverer);
dropRecoveringInvalidationControllers.put(objectName, dropRecoveringInvalidationController);
} else {
dropRecoveringInvalidationController = null;
}
return new RemovableHandle() {
@Override
public void initializeRecoverer(long nextExpectedVersion) {
Preconditions.checkState(dropRecoveringInvalidationController != null,
"You did need initialize a recoverer for this object: " + objectId);
Preconditions.checkArgument(nextExpectedVersion >= InvalidationUtils.INITIAL_OBJECT_VERSION,
"You can't initialize the recoverer to a value < " + InvalidationUtils.INITIAL_OBJECT_VERSION
+ ": " + objectId + "(" + nextExpectedVersion + ")");
// TODO: Fix up the long vs int debacle.
dropRecoveringInvalidationController.setNextExpectedVersion((int) nextExpectedVersion);
}
@Override
public void remove() {
unregister(objectId);
}
};
}
/**
* Unregisters an object Id.
*/
@Override
public void unregister(InvalidationObjectId<?> objectId) {
logger.fine("Unregistering object Id: %s", objectId);
final String objectName = objectId.getName();
listenerMap.remove(objectName);
DropRecoveringInvalidationController dropRecoveringInvalidationController =
dropRecoveringInvalidationControllers.remove(objectName);
if (dropRecoveringInvalidationController != null) {
dropRecoveringInvalidationController.cleanup();
}
}
public void handleInvalidation(String name, long version, @Nullable String payload) {
logger.fine("Invalidation for %s: Version: %s Payload: %s", name, version, payload);
InvalidationRegistrar.Listener listener = listenerMap.get(name);
if (listener == null) {
logger.severe("The listener does not exist for this objectId: %s", name);
return;
}
DropRecoveringInvalidationController dropRecoveringInvalidationController =
dropRecoveringInvalidationControllers.get(name);
if (dropRecoveringInvalidationController != null) {
// we check if the payload is the special string indicating null
boolean isEmptyPayload = payload != null && payload.equals(InvalidationObjectId.EMPTY_PAYLOAD);
dropRecoveringInvalidationController.handleInvalidated(
isEmptyPayload ? null : payload, version, isEmptyPayload);
} else {
listener.onInvalidated(name, version, payload, null);
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/clientlibs/navigation/UrlComponentEncoder.java | client/src/main/java/com/google/collide/clientlibs/navigation/UrlComponentEncoder.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.clientlibs.navigation;
/**
* An object which can encode and decode url components safely.
*/
interface UrlComponentEncoder {
public String encode(String text);
public String decode(String text);
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/clientlibs/navigation/NavigationTokenImpl.java | client/src/main/java/com/google/collide/clientlibs/navigation/NavigationTokenImpl.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.clientlibs.navigation;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.shared.util.JsonCollections;
/**
* A basic history token which represents a chunk of history decoded from a url.
*
*/
class NavigationTokenImpl implements NavigationToken {
private final String placeName;
private final JsonStringMap<String> placeData = JsonCollections.createMap();
NavigationTokenImpl(String placeName) {
this.placeName = placeName;
}
@Override
public String getPlaceName() {
return placeName;
}
@Override
public JsonStringMap<String> getBookmarkableState() {
return placeData;
}
@Override
public String toString() {
return placeName + placeData.toString();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/clientlibs/navigation/UrlSerializer.java | client/src/main/java/com/google/collide/clientlibs/navigation/UrlSerializer.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.clientlibs.navigation;
import com.google.collide.json.shared.JsonArray;
/**
* An object which can serialize a list of HistoryToken's to a url.
*/
public interface UrlSerializer {
/** The separator to be used in separating url paths */
public static final String PATH_SEPARATOR = "/";
/**
* Deserializes a url into a list of history tokens.
*
* @param url the url is guaranteed to start with a {@link #PATH_SEPARATOR}
*/
public JsonArray<NavigationToken> deserialize(String url);
/**
* @return a serialized url or null if unable to serialize.
*/
public String serialize(JsonArray<? extends NavigationToken> tokens);
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/clientlibs/navigation/DefaultUrlSerializer.java | client/src/main/java/com/google/collide/clientlibs/navigation/DefaultUrlSerializer.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.clientlibs.navigation;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.json.shared.JsonStringMap.IterationCallback;
import com.google.collide.shared.util.JsonCollections;
import com.google.collide.shared.util.StringUtils;
/**
* A serializer which serializes all data in each {@link NavigationToken}'s map to the url. The
* resulting url is not really that pretty.
*
*/
class DefaultUrlSerializer implements UrlSerializer {
static final char KEY_VALUE_SEPARATOR = '=';
private final UrlComponentEncoder encoder;
public DefaultUrlSerializer(UrlComponentEncoder encoder) {
this.encoder = encoder;
}
@Override
public JsonArray<NavigationToken> deserialize(String url) {
JsonArray<NavigationToken> tokens = JsonCollections.createArray();
// Simple parser, we pass the first PATH_SEPARATOR then split the string and
// look for a place name followed by any mapped contents it may have.
JsonArray<String> components = StringUtils.split(url.substring(1), PATH_SEPARATOR);
for (int i = 0; i < components.size();) {
String encodedPlace = components.get(i);
String decodedPlace = encoder.decode(encodedPlace);
// Create a token for the decoded place
NavigationToken token = new NavigationTokenImpl(decodedPlace);
tokens.add(token);
// Loop through adding map values until we encounter the next place
for (i++; i < components.size(); i++) {
String encodedKeyValue = components.get(i);
int separatorIndex = encodedKeyValue.indexOf(KEY_VALUE_SEPARATOR);
if (separatorIndex == -1) {
// we are back to a place and should let the outer loop restart
break;
}
// Grab the encoded values
String encodedKey = encodedKeyValue.substring(0, separatorIndex);
String encodedValue = encodedKeyValue.substring(separatorIndex + 1);
// decode and place in the map
String decodedKey = encoder.decode(encodedKey);
String decodedValue = encoder.decode(encodedValue);
token.getBookmarkableState().put(decodedKey, decodedValue);
}
}
return tokens;
}
/**
* This serializes a URL into a simple format consisting of /place/key=value/key=value/place/...
*
* @return This serializer will never return null and can always serialize a list of
* {@link NavigationToken}s.
*/
@Override
public String serialize(JsonArray<? extends NavigationToken> tokens) {
final StringBuilder urlBuilder = new StringBuilder();
for (int i = 0; i < tokens.size(); i++) {
NavigationToken token = tokens.get(i);
String encodedName = encoder.encode(token.getPlaceName());
urlBuilder.append(PATH_SEPARATOR).append(encodedName);
JsonStringMap<String> tokenData = token.getBookmarkableState();
tokenData.iterate(new IterationCallback<String>() {
@Override
public void onIteration(String key, String value) {
// omit explicit nulls
if (value == null) {
return;
}
String encodedKey = encoder.encode(key);
String encodedValue = encoder.encode(value);
urlBuilder.append(PATH_SEPARATOR)
.append(encodedKey).append(KEY_VALUE_SEPARATOR).append(encodedValue);
}
});
}
return urlBuilder.toString();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/clientlibs/navigation/UrlSerializationController.java | client/src/main/java/com/google/collide/clientlibs/navigation/UrlSerializationController.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.clientlibs.navigation;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.util.JsonCollections;
import com.google.collide.shared.util.StringUtils;
import elemental.client.Browser;
/**
* A controller which can serialize and deserialize pieces of history to a url.
*/
public class UrlSerializationController {
/**
* A {@link UrlComponentEncoder} which uses the browser's decode and encode component
* methods.
*/
private static final UrlComponentEncoder urlEncoder = new UrlComponentEncoder() {
@Override
public String decode(String text) {
return Browser.decodeURIComponent(text);
}
@Override
public String encode(String text) {
return Browser.encodeURIComponent(text);
}
};
/** The default serializer to use */
private final UrlSerializer defaultSerializer = new DefaultUrlSerializer(urlEncoder);
/**
* Deserializes a URL into a list of NavigationTokens.
*
* @param serializedUrl should not be null and must start with a
* {@link UrlSerializer#PATH_SEPARATOR} to distinguish it from other
* hash values.
*/
public JsonArray<NavigationToken> deserializeFromUrl(String serializedUrl) {
// We attempted to parse an invalid url
if (StringUtils.isNullOrEmpty(serializedUrl)
|| serializedUrl.indexOf(UrlSerializer.PATH_SEPARATOR) != 0) {
return JsonCollections.createArray();
}
return defaultSerializer.deserialize(serializedUrl);
}
/**
* Serializes a list of history tokens identifying a unique application state
* to a url.
*
* @return a url identifying this list of history tokens. It will always start
* with {@link UrlSerializer#PATH_SEPARATOR}.
*/
public String serializeToUrl(JsonArray<? extends NavigationToken> historyTokens) {
String url = defaultSerializer.serialize(historyTokens);
return StringUtils.ensureStartsWith(url, "/");
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/clientlibs/navigation/NavigationToken.java | client/src/main/java/com/google/collide/clientlibs/navigation/NavigationToken.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.clientlibs.navigation;
import com.google.collide.json.shared.JsonStringMap;
/**
* A token used to identify a unique segment of history.
*/
public interface NavigationToken {
/**
* @return the unique name identifying the place of this token.
*/
public String getPlaceName();
/**
* @return The serialized data contained in this token.
*/
public JsonStringMap<String> getBookmarkableState();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/clientlibs/network/shared/WorkspaceImpl.java | client/src/main/java/com/google/collide/clientlibs/network/shared/WorkspaceImpl.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.clientlibs.network.shared;
import com.google.collide.clientlibs.model.Workspace;
import com.google.collide.dto.GetWorkspaceMetaDataResponse;
/**
* An implementation of the {@link Workspace} interface. This object wraps a
* workspaceInfo object so clients don't get a direct handle to the javascript
* object. This allows us to easily change out the WorkspaceInfo with an updated
* one from the server without inconveniencing clients.
*/
public class WorkspaceImpl implements Workspace {
private GetWorkspaceMetaDataResponse workspaceInfo;
public WorkspaceImpl(GetWorkspaceMetaDataResponse workspaceInfo) {
this.workspaceInfo = workspaceInfo;
}
@Override
public GetWorkspaceMetaDataResponse getWorkspaceMetaData() {
return workspaceInfo;
}
@Override
public String getOwningProjectId() {
// TODO: Resurrect UX for branch switching.
return "";
}
@Override
public String toString() {
return "Workspace: " + workspaceInfo.getWorkspaceName();
}
public void setWorkspaceInfo(GetWorkspaceMetaDataResponse workspaceInfo) {
this.workspaceInfo = workspaceInfo;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/clientlibs/network/shared/RequestMerger.java | client/src/main/java/com/google/collide/clientlibs/network/shared/RequestMerger.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.clientlibs.network.shared;
import com.google.collide.client.util.QueryCallback;
import com.google.collide.dto.ServerError.FailureReason;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.shared.util.JsonCollections;
import com.google.common.base.Joiner;
/**
* An object which prevents multiple identical requests from being sent across
* the wire to the frontend. When a new requests matches an existing request its
* callback is queued. After the initial request returns all callbacks are
* notified of success or failure. This object should only be used for requests
* which cause no server-side side effects (i.e. creating project).
*
* @param <R> The type sent to the query callback on success or failure
*/
public class RequestMerger<R> {
/**
* Static factory to create a RequestMerger
*
* @param <R> Type sent to the query callback
*/
public static <R> RequestMerger<R> create() {
return new RequestMerger<R>();
}
/**
* Convenience constant for merging all requests.
*/
public static final String ALL_REQUESTS = "ALL";
private JsonStringMap<JsonArray<QueryCallback<R>>> requestMap = JsonCollections.createMap();
/**
* Adds a new request to the map, returning true if the exact requestHash is a
* currently outstanding request and should not be sent over the wire.
*
* @param requestHash Unique hash identifying this request's parameters.
* @param callback Callback to call on success/failure.
*
* @return true to indicate that this is a new request, false to indicate that
* it is a duplicate of an existing request and has been queued.
*/
public boolean handleNewRequest(String requestHash, QueryCallback<R> callback) {
JsonArray<QueryCallback<R>> callbacks = requestMap.get(requestHash);
boolean existed = callbacks != null;
if (callbacks == null) {
callbacks = JsonCollections.createArray();
requestMap.put(requestHash, callbacks);
}
callbacks.add(callback);
return !existed;
}
/**
* Call to notify all callbacks waiting on a request of failure.
*/
public void handleQueryFailed(String requestHash, FailureReason reason) {
JsonArray<QueryCallback<R>> callbacks = requestMap.remove(requestHash);
if (callbacks == null) {
return;
}
for (int i = 0; i < callbacks.size(); i++) {
callbacks.get(i).onFail(reason);
}
}
/**
* Handles notifying all callbacks waiting on a request of success.
*/
public void handleQuerySuccess(String requestHash, R result) {
JsonArray<QueryCallback<R>> callbacks = requestMap.remove(requestHash);
if (callbacks == null) {
return;
}
for (int i = 0; i < callbacks.size(); i++) {
callbacks.get(i).onQuerySuccess(result);
}
}
/**
* Clears any callbacks waiting on the given request.
*/
public void clearCallbacksWaitingForRequest(String requestHash) {
requestMap.remove(requestHash);
}
/**
* @return the number of callbacks merged and waiting on a given request.
*/
public boolean hasCallbacksWaitingForRequest(String requestHash) {
JsonArray<QueryCallback<R>> callbacks = requestMap.get(requestHash);
return callbacks != null && callbacks.size() > 0;
}
/**
* Creates a '|' separated hash string from a list of string values. Calls
* {@link Object#toString()} on each value passed in to make the hash.
*/
public static String createHash(Object... values) {
return Joiner.on("|").join(values);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/clientlibs/network/shared/StatusMessageUtils.java | client/src/main/java/com/google/collide/clientlibs/network/shared/StatusMessageUtils.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.clientlibs.network.shared;
import com.google.collide.client.status.StatusManager;
import com.google.collide.client.status.StatusMessage;
import com.google.collide.client.status.StatusMessage.MessageType;
/**
* Some utils for displaying common network error type status messages.
*/
public class StatusMessageUtils {
/**
* Creates a reloadable and dismissable error {@link StatusMessage}. {@link StatusMessage#fire()}
* must be called before it is shown to the user.
*/
public static StatusMessage createReloadableDismissableErrorStatus(
StatusManager manager, String title, String longText) {
StatusMessage error = StatusMessageUtils.createDismissableErrorStatus(manager, title, longText);
error.addAction(StatusMessage.RELOAD_ACTION);
return error;
}
/**
* Creates a dismissable error {@link StatusMessage}. {@link StatusMessage#fire()} must be called
* before it is shown to the user.
*/
public static StatusMessage createDismissableErrorStatus(
StatusManager manager, String title, String longText) {
StatusMessage error = new StatusMessage(manager, MessageType.ERROR, title);
error.setLongText(longText);
error.setDismissable(true);
return error;
}
private StatusMessageUtils() {
// Static utility class
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/clientlibs/network/shared/WorkspaceCache.java | client/src/main/java/com/google/collide/clientlibs/network/shared/WorkspaceCache.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.clientlibs.network.shared;
import com.google.collide.clientlibs.model.Workspace;
import com.google.collide.dto.GetWorkspaceMetaDataResponse;
import com.google.collide.dto.WorkspaceInfo;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.shared.util.JsonCollections;
/**
* A cache which contains any and all {@link Workspace} objects. In the current implementation
* user's can only access a single workspace but in this helps us handle multiple workspaces in the
* future.
*
*/
public class WorkspaceCache {
/**
* Map of workspace ID -> {@link WorkspaceInfo}
*/
private final JsonStringMap<WorkspaceImpl> branches = JsonCollections.createMap();
/**
* Returns true if a workspace exists in the cache.
*/
public boolean isWorkspaceCached(String branchId) {
return getCachedWorkspaceById(branchId) != null;
}
/**
* Returns the {@link WorkspaceInfo} referred to by the workspace ID from the
* cache.
*/
public WorkspaceImpl getCachedWorkspaceById(String branchId) {
return branches.get(branchId);
}
/**
* Caches a workspace; updates the cached {@link Workspace}'s {@link WorkspaceInfo} if it is
* already cached.
*
* @return the cached {@link Workspace}.
*/
public WorkspaceImpl cacheWorkspace(
String workspaceId, final GetWorkspaceMetaDataResponse workspaceInfo) {
WorkspaceImpl workspace = getCachedWorkspaceById(workspaceId);
if (workspace == null) {
workspace = new WorkspaceImpl(workspaceInfo);
branches.put(workspaceId, workspace);
} else {
workspace.setWorkspaceInfo(workspaceInfo);
}
return workspace;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/clientlibs/network/shared/WorkspaceInfoMutator.java | client/src/main/java/com/google/collide/clientlibs/network/shared/WorkspaceInfoMutator.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.clientlibs.network.shared;
import com.google.collide.dto.RunTarget;
import com.google.collide.dto.WorkspaceInfo;
import com.google.collide.dto.client.DtoClientImpls.WorkspaceInfoImpl;
/**
* A helper class which does some casting which may not be valid for unit tests. Nothing really
* requires us to do this in a helper but it is nice.
*/
public class WorkspaceInfoMutator {
/**
* Updates a workspace's {@link RunTarget}.
*/
public void updateRunTarget(WorkspaceInfo workspace, RunTarget target) {
WorkspaceInfoImpl workspaceImpl = (WorkspaceInfoImpl) workspace;
workspaceImpl.setRunTarget(target);
}
} | java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/codemirror2/PyState.java | client/src/main/java/com/google/collide/codemirror2/PyState.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.codemirror2;
/**
* Object that represents py-parser state.
*/
public class PyState extends CmState {
protected PyState() {
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/codemirror2/CmState.java | client/src/main/java/com/google/collide/codemirror2/CmState.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.codemirror2;
import com.google.gwt.core.client.JavaScriptObject;
/**
* A wrapper around the JSO state mutated by a parser mode. This is usually a
* dictionary of mode-specific state information, such as a stack of HTML tags
* to close or the next expected character.
*/
public class CmState extends JavaScriptObject implements State {
protected CmState() {
}
@Override
public final native State copy(Parser mode) /*-{
var copiedState = $wnd.CodeMirror.copyState(mode, this);
// Workaround for Chrome devmode: Remove the devmode workaround for Chrome
// object identity. For 100% correctness, this should iterate through
// and remove all instances of __gwtObjectId, but the top-level was
// sufficient from my testing.
delete copiedState.__gwt_ObjectId;
return copiedState;
}-*/;
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/codemirror2/CmParser.java | client/src/main/java/com/google/collide/codemirror2/CmParser.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.codemirror2;
import com.google.collide.json.shared.JsonArray;
import com.google.common.annotations.VisibleForTesting;
import com.google.gwt.core.client.JavaScriptObject;
/**
* One of the CodeMirror2 parsing modes, with utilities for saving/restoring the
* parser state and returning a list of tokens for a string of text.
*
*/
public class CmParser extends JavaScriptObject implements Parser {
protected CmParser() {
}
private native void setTypeAndName(SyntaxType type, String name) /*-{
this.syntaxType = type;
this.parserName = name;
}-*/;
@Override
public final State defaultState() {
return getStartState();
}
@Override
public final void parseNext(Stream stream, State state, JsonArray<Token> tokens) {
String tokenName = token(stream, state);
String tokenValue = updateStreamPosition(stream);
getSyntaxType().getTokenFactory().push(getName(state), state, tokenName, tokenValue, tokens);
}
private native String token(Stream stream, State state) /*-{
return this.token(stream, state);
}-*/;
/**
* Advance the stream index pointers.
*
* @return a String with the remaining stream contents to be parsed.
*/
private native String updateStreamPosition(Stream stream) /*-{
var value = stream.string.slice(stream.start, stream.pos);
stream.start = stream.pos;
return value;
}-*/;
private native CmState getStartState() /*-{
var state = $wnd.CodeMirror.startState(this);
return (state === true) ? {} : state;
}-*/;
@Override
public final native String getName(State state) /*-{
return state.mode || this.parserName;
}-*/;
@Override
public final native boolean hasSmartIndent() /*-{
return (this.indent && !this.__preventSmartIndent) ? true : false;
}-*/;
@Override
public final native int indent(State stateAbove, String text) /*-{
if (this.indent && stateAbove) {
return this.indent(stateAbove, text);
}
return -1;
}-*/;
final native void setPreventSmartIndent(boolean preventSmartIndent) /*-{
this.__preventSmartIndent = preventSmartIndent;
}-*/;
@VisibleForTesting
protected final void setType(SyntaxType type) {
setTypeAndName(type, type.getName());
}
@Override
public final native SyntaxType getSyntaxType() /*-{
return this.syntaxType;
}-*/;
@Override
public final native Stream createStream(String text) /*-{
return new $wnd.CodeMirror.StringStream(text);
}-*/;
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/codemirror2/XmlState.java | client/src/main/java/com/google/collide/codemirror2/XmlState.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.codemirror2;
/**
* Object that represents xml-parser state.
*
*/
public class XmlState extends CmState {
protected XmlState() {
}
public final native XmlContext getContext() /*-{
return this.context;
}-*/;
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/codemirror2/CssState.java | client/src/main/java/com/google/collide/codemirror2/CssState.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.codemirror2;
import com.google.collide.json.shared.JsonArray;
/**
* Object that represents css-parser state.
*
*/
public class CssState extends CmState {
protected CssState() {
}
final native JsonArray<String> getStack() /*-{
return this.stack;
}-*/;
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/codemirror2/HtmlTokenFactory.java | client/src/main/java/com/google/collide/codemirror2/HtmlTokenFactory.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.codemirror2;
import com.google.collide.json.shared.JsonArray;
/**
* Token factory for HTML. Depending on the mode it creates either {@link Token}
* or {@link CssToken}.
*
* <p>By creating {@link CssToken} we capture the context which is part of the
* {@link CssState}.
*/
class HtmlTokenFactory implements TokenFactory<HtmlState> {
@Override
public void push(String stylePrefix, HtmlState htmlState, String tokenType, String tokenValue,
JsonArray<Token> tokens) {
Token token;
if (CodeMirror2.CSS.equals(stylePrefix)) {
CssState cssState = htmlState.getCssState();
token = CssTokenFactory.createToken(stylePrefix, cssState, tokenType, tokenValue);
} else {
token =
new Token(stylePrefix, TokenType.resolveTokenType(tokenType, tokenValue), tokenValue);
}
tokens.add(token);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/codemirror2/Stream.java | client/src/main/java/com/google/collide/codemirror2/Stream.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.codemirror2;
/**
* Abstraction of Codemirror StringStream object.
*/
public interface Stream {
/**
* @return {@code true} if all data has been consumed
*/
boolean isEnd();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/codemirror2/TokenUtil.java | client/src/main/java/com/google/collide/codemirror2/TokenUtil.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.codemirror2;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.shared.Pair;
import com.google.collide.shared.util.JsonCollections;
import com.google.collide.shared.util.StringUtils;
import com.google.common.annotations.VisibleForTesting;
/**
* Codemirror2 {@link Token} related utilities.
*/
public class TokenUtil {
/**
* Map ["mode:width"] -> whitespace token of given mode and width.
*
* <p>Used by {@link #getPlaceholderForMode} to cache placeholder tokens.
*/
private static final JsonStringMap<Token> cachedPlaceholders = JsonCollections.createMap();
// Do not instantiate.
private TokenUtil() {}
/**
* <p>Finds the mode (programming language) corresponding to the given column:
* <ul>
* <li>If the column is inside a token then the mode of the token is returned
* <li>if the column is on the boundary between two tokens then the mode of
* the first token is returned (this behavior works well for auto-completion)
* <li>if the column is greater than the sum of all token lengths then the
* mode of the last token is returned (so that we handle auto-completion for
* fast typer in the best possible way)
* <li>if the map is empty then null is returned
* <li>if the column = 0 then the mode of the first tag is returned
* <li>if the column is < 0 then IllegalArgumentException is thrown
* </ul>
*
* @param initialMode mode before the first token.
* @param modes "language map" built by {@link #buildModes}
* @param column column to search for
* @return the mode of the token covering the column
* @throws IllegalArgumentException if the column is < 0
*/
public static String findModeForColumn(
String initialMode, @Nonnull JsonArray<Pair<Integer, String>> modes, int column) {
if (column < 0) {
throw new IllegalArgumentException("Column should be >= 0 but was " + column);
}
String mode = initialMode;
for (Pair<Integer, String> pair : modes.asIterable()) {
if (pair.first >= column) {
// We'll use last remembered mode.
break;
}
mode = pair.second;
}
return mode;
}
/**
* Builds a "language map".
*
* <p>Language map is an array of pairs {@code (column, mode)}, where column
* is the boundary between previous mode and current mode.
*
* <p>The array is ordered by the column.
*
* @param initialMode mode before the first token
* @param tokens tokens from which to build the map
* @return array of pairs (column, mode)
*/
@Nonnull
public static JsonArray<Pair<Integer, String>> buildModes(
@Nullable String initialMode, @Nonnull JsonArray<Token> tokens) {
JsonArray<Pair<Integer, String>> modes = JsonCollections.createArray();
String currentMode = initialMode;
int currentColumn = 0;
for (Token token : tokens.asIterable()) {
if (token.getType() == TokenType.NEWLINE) {
// Avoid "brandless" mode to be the last mode in the map.
break;
}
String mode = token.getMode();
if (!mode.equals(currentMode)) {
modes.add(new Pair<Integer, String>(currentColumn, mode));
currentMode = mode;
}
currentColumn += token.getValue().length();
}
return modes;
}
@VisibleForTesting
static void addPlaceholders(String mode, JsonStringMap<JsonArray<Token>> splitTokenMap,
int width) {
for (String key : splitTokenMap.getKeys().asIterable()) {
if (!key.equals(mode)) {
splitTokenMap.get(key).add(getPlaceholderForMode(key, width));
}
}
}
private static Token getPlaceholderForMode(String mode, int width) {
String key = mode + ":" + width;
if (cachedPlaceholders.containsKey(key)) {
return cachedPlaceholders.get(key);
}
Token token = new Token(mode, TokenType.WHITESPACE, StringUtils.getSpaces(width));
cachedPlaceholders.put(key, token);
return token;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/codemirror2/BasicTokenFactory.java | client/src/main/java/com/google/collide/codemirror2/BasicTokenFactory.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.codemirror2;
import com.google.collide.json.shared.JsonArray;
/**
* Token factory that do not use information from {@link State}.
*/
class BasicTokenFactory implements TokenFactory<State> {
@Override
public void push(String stylePrefix, State state, String tokenType, String tokenValue,
JsonArray<Token> tokens) {
tokens.add(new Token(
stylePrefix, TokenType.resolveTokenType(tokenType, tokenValue), tokenValue));
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/codemirror2/JsLocalVariable.java | client/src/main/java/com/google/collide/codemirror2/JsLocalVariable.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.codemirror2;
import com.google.gwt.core.client.JavaScriptObject;
/**
* Element of linked list of local variables in {@link JsState}.
*/
public class JsLocalVariable extends JavaScriptObject {
protected JsLocalVariable() {
}
public final native String getName() /*-{
return this.name;
}-*/;
public final native JsLocalVariable getNext() /*-{
return this.next;
}-*/;
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/codemirror2/State.java | client/src/main/java/com/google/collide/codemirror2/State.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.codemirror2;
/**
* Interface that represents CodeMirror state.
*/
public interface State {
/**
* Clones the object.
*
* <p>Parser parameter is used by native CodeMirror implementation.
*
* @param codeMirrorParser parser that created this instance
*/
State copy(Parser codeMirrorParser);
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/codemirror2/CssTokenFactory.java | client/src/main/java/com/google/collide/codemirror2/CssTokenFactory.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.codemirror2;
import com.google.collide.json.shared.JsonArray;
/**
* Token factory for CSS; uses information from {@link CssState}.
*/
public class CssTokenFactory implements TokenFactory<CssState> {
@Override
public void push(String stylePrefix, CssState state, String tokenType, String tokenValue,
JsonArray<Token> tokens) {
tokens.add(createToken(stylePrefix, state, tokenType, tokenValue));
}
/**
* Create new {@link CssToken} for the given parameters.
*
* <p>This method is shared with {@link HtmlTokenFactory} in order to create
* tokens of class {@link CssToken} for internal style sheets.
*
* @param stylePrefix a.k.a. mode, in this case expected to be "css"
* @param state CSS parser state at the time when the token was parsed
* @param tokenType token type
* @param tokenValue token value
* @return newly created {@link CssToken}.
*/
static CssToken createToken(String stylePrefix, CssState state, String tokenType,
String tokenValue) {
JsonArray<String> stack = state.getStack();
String context = (stack != null && stack.size() > 0) ? stack.peek() : null;
return new CssToken(stylePrefix, TokenType.resolveTokenType(tokenType, tokenValue), tokenValue,
context);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/codemirror2/SyntaxType.java | client/src/main/java/com/google/collide/codemirror2/SyntaxType.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.codemirror2;
import com.google.collide.client.util.PathUtil;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.shared.util.JsonCollections;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
/**
* Syntax types (languages / file formats) enumeration.
*/
@SuppressWarnings("rawtypes")
public enum SyntaxType {
CPP("clike", "text/x-c++src", State.class, new BasicTokenFactory(), false),
CSS("css", "text/css", CssState.class, new CssTokenFactory(), true),
DART("dart", "text/dart", State.class, new BasicTokenFactory(), false),
GO("go", "text/x-go", State.class, new BasicTokenFactory(), false),
HTML("html", "text/html", HtmlState.class, new HtmlTokenFactory(), true),
JAVA("clike", "text/x-java", State.class, new BasicTokenFactory(), false),
JS("javascript", "text/javascript", JsState.class, new BasicTokenFactory(), true),
NONE("unknown", "text/plain", State.class, new BasicTokenFactory(), true),
PHP("php", "text/x-php", State.class, new BasicTokenFactory(), false),
PY("python", "text/x-python", PyState.class, new PyTokenFactory(), false),
SVG("xml", "application/xml", State.class, new BasicTokenFactory(), true),
XML("xml", "application/xml", State.class, new BasicTokenFactory(), true),
YAML("yaml", "text/x-yaml", State.class, new BasicTokenFactory(), true);
/**
* Guesses syntax type by file path.
*/
@VisibleForTesting
public static SyntaxType syntaxTypeByFilePath(PathUtil filePath) {
Preconditions.checkNotNull(filePath);
return syntaxTypeByFileName(filePath.getBaseName());
}
/**
* Guesses syntax type by file name.
*/
public static SyntaxType syntaxTypeByFileName(String fileName) {
Preconditions.checkNotNull(fileName);
SyntaxType syntaxType = extensionToSyntaxType.get(PathUtil.getFileExtension(
fileName.toLowerCase()));
return (syntaxType != null) ? syntaxType : SyntaxType.NONE;
}
private final String mimeType;
private final TokenFactory tokenFactory;
private final Class stateClass;
private final String name;
private final boolean hasGlobalNamespace;
private static final JsonStringMap<SyntaxType> extensionToSyntaxType =
createExtensionToSyntaxTypeMap();
public String getMimeType() {
return mimeType;
}
public String getName() {
return name;
}
@SuppressWarnings("unchecked")
public <T extends State> TokenFactory<T> getTokenFactory() {
return tokenFactory;
}
SyntaxType(String name, String mimeType, Class<? extends State> stateClass,
TokenFactory tokenFactory, boolean hasGlobalNamespace) {
this.name = name;
this.mimeType = mimeType;
this.tokenFactory = tokenFactory;
this.stateClass = stateClass;
this.hasGlobalNamespace = hasGlobalNamespace;
}
/**
* Checks if specified class can be cast form parser state corresponding to
* this syntax type.
*
* @param stateClass class we are going to (down)cast to
* @return {@code true} is cast can be performed safely
*/
public boolean checkStateClass(Class stateClass) {
return stateClass == this.stateClass || stateClass == State.class;
}
/**
* @return {@code true} if this syntax type has a notion of global namespace, as opposed
* to the notion of modules and explicit importing
*/
public boolean hasGlobalNamespace() {
return hasGlobalNamespace;
}
/**
* Initializes extension -> syntax type map. <b>All extension keys must be lowercase</b>.
* @return a new map instance with all supported languages.
*/
private static JsonStringMap<SyntaxType> createExtensionToSyntaxTypeMap() {
JsonStringMap<SyntaxType> tmp = JsonCollections.createMap();
tmp.put("cc", SyntaxType.CPP);
tmp.put("cpp", SyntaxType.CPP);
tmp.put("css", SyntaxType.CSS);
tmp.put("cxx", SyntaxType.CPP);
tmp.put("dart", SyntaxType.DART);
tmp.put("go", SyntaxType.GO);
tmp.put("hpp", SyntaxType.CPP);
tmp.put("h", SyntaxType.CPP);
tmp.put("html", SyntaxType.HTML);
tmp.put("hxx", SyntaxType.CPP);
tmp.put("java", SyntaxType.JAVA);
tmp.put("js", SyntaxType.JS);
tmp.put("php", SyntaxType.PHP);
tmp.put("py", SyntaxType.PY);
tmp.put("svg", SyntaxType.SVG);
tmp.put("xml", SyntaxType.XML);
tmp.put("yaml", SyntaxType.YAML);
return tmp;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/codemirror2/TokenFactory.java | client/src/main/java/com/google/collide/codemirror2/TokenFactory.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.codemirror2;
import com.google.collide.json.shared.JsonArray;
/**
* Factory that produces mode-specific {@link Token}s.
*
* @param <T> specific state type
*/
public interface TokenFactory<T extends State> {
/**
* Creates tokens based on parser, mode and parse results, and appends them to
* tokens array.
*/
void push(String stylePrefix, T state, String tokenType, String tokenValue,
JsonArray<Token> tokens);
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/codemirror2/PyTokenFactory.java | client/src/main/java/com/google/collide/codemirror2/PyTokenFactory.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.codemirror2;
import static com.google.collide.codemirror2.Token.LITERAL_PERIOD;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringSet;
import com.google.collide.shared.util.JsonCollections;
import com.google.collide.shared.util.StringUtils;
/**
* Token factory that splits some PY tokens to more canonical ones.
*
*/
class PyTokenFactory implements TokenFactory<State> {
private static final JsonStringSet KEYWORD_OPERATORS = JsonCollections.createStringSet(
"and", "in", "is", "not", "or");
@Override
public void push(String stylePrefix, State state, String tokenType, String tokenValue,
JsonArray<Token> tokens) {
TokenType type = TokenType.resolveTokenType(tokenType, tokenValue);
if (TokenType.VARIABLE == type) {
if (tokenValue.startsWith(LITERAL_PERIOD)) {
tokens.add(new Token(stylePrefix, TokenType.NULL, LITERAL_PERIOD));
tokenValue = tokenValue.substring(1);
// TODO: Also cut whitespace (after fixes in CodeMirror).
}
} else if (TokenType.OPERATOR == type) {
if (KEYWORD_OPERATORS.contains(tokenValue)) {
type = TokenType.KEYWORD;
}
} else if (TokenType.ERROR == type) {
// When parser finds ":" it pushes a new context and specifies indention
// equal to previous indention + some configured amount. If the next line
// indention is less than specified then whitespace is marked as ERROR.
if (StringUtils.isNullOrWhitespace(tokenValue)) {
type = TokenType.WHITESPACE;
}
}
tokens.add(new Token(stylePrefix, type, tokenValue));
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/codemirror2/DartState.java | client/src/main/java/com/google/collide/codemirror2/DartState.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.codemirror2;
/**
* Dart parser state.
*/
public class DartState extends CmState {
protected DartState() {
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/codemirror2/Token.java | client/src/main/java/com/google/collide/codemirror2/Token.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.codemirror2;
/**
* A representation of a single Codemirror2 token.
*
* <p>A token consists of a type (function, keyword, variable, etc), and a value
* (the piece of code that is classified as a single token of the same type).
*
*/
public class Token {
public static final Token NEWLINE = new Token("", TokenType.NEWLINE, "\n");
public static final String LITERAL_PERIOD = ".";
private final String mode;
private final TokenType type;
private final String value;
public Token(String mode, TokenType type, String value) {
this.mode = mode;
this.type = type;
this.value = value;
}
public TokenType getType() {
return type;
}
public String getValue() {
return value;
}
public String getMode() {
return mode;
}
/**
* @return the type prefixed with the parsing mode it was found in
*/
public final String getStyle() {
return mode + "-" + type.getTypeName();
}
@Override
public String toString() {
return "Token{"
+ "mode='" + mode + '\''
+ ", type=" + type
+ ", value='" + value + '\''
+ '}';
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/codemirror2/CssToken.java | client/src/main/java/com/google/collide/codemirror2/CssToken.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.codemirror2;
/**
* Token that knows about CSS state stack.
*/
public class CssToken extends Token {
/**
* CSS parsing context is the value at the top of state stack.
*/
private final String context;
CssToken(String mode, TokenType type, String value, String context) {
super(mode, type, value);
this.context = context;
}
public String getContext() {
return context;
}
@Override
public String toString() {
return "CssToken{"
+ "mode='" + getMode() + '\''
+ ", type=" + getType()
+ ", value='" + getValue() + '\''
+ ", context='" + context + '\''
+ '}';
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/codemirror2/JsState.java | client/src/main/java/com/google/collide/codemirror2/JsState.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.codemirror2;
/**
* Object that represents js-parser state.
*/
public class JsState extends CmState {
protected JsState() {
}
public final native JsLocalVariable getLocalVariables() /*-{
if (this.mode == "javascript") {
return this.localState.localVars;
} else {
return this.localVars;
}
}-*/;
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/codemirror2/CodeMirror2.java | client/src/main/java/com/google/collide/codemirror2/CodeMirror2.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.codemirror2;
import com.google.collide.client.util.PathUtil;
import com.google.common.base.Preconditions;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.TextResource;
/**
* Wraps the CodeMirror2 syntax parser modes.
*
*/
public class CodeMirror2 {
/**
* External parser javascript source.
*/
public interface Resources extends ClientBundle {
@Source("codemirror2_parsers.js")
TextResource parser();
@Source("codemirror2_base.js")
TextResource base();
}
public static String getJs(Resources resources) {
return resources.base().getText() + resources.parser().getText();
}
public static Parser getParser(PathUtil path) {
SyntaxType type = SyntaxType.syntaxTypeByFilePath(path);
CmParser parser = getParserForMime(type.getMimeType());
Preconditions.checkNotNull(parser);
parser.setType(type);
// TODO: testing no smart indentation to see how it feels
parser.setPreventSmartIndent(type != SyntaxType.PY);
return parser;
}
private static native CmParser getParserForMime(String mime) /*-{
conf = $wnd.CodeMirror.defaults;
if (mime == "text/x-python") {
conf["mode"] = {
version : 2
};
}
return $wnd.CodeMirror.getMode(conf, mime);
}-*/;
/**
* Mode constant: JavaScript.
*/
public static final String JAVASCRIPT = "javascript";
/**
* Mode constant: HTML.
*/
public static final String HTML = "html";
/**
* Mode constant: CSS.
*/
public static final String CSS = "css";
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/codemirror2/CmStream.java | client/src/main/java/com/google/collide/codemirror2/CmStream.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.codemirror2;
import com.google.gwt.core.client.JavaScriptObject;
/**
* Native CodeMirror {@link Stream} wrapper.
*/
public class CmStream extends JavaScriptObject implements Stream {
protected CmStream() {
}
@Override
public final native boolean isEnd() /*-{
return this.eol();
}-*/;
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/codemirror2/HtmlState.java | client/src/main/java/com/google/collide/codemirror2/HtmlState.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.codemirror2;
/**
* Object that represents html-parser state.
*
*/
public class HtmlState extends CmState {
protected HtmlState() {
}
public final native XmlState getXmlState() /*-{
return this.htmlState;
}-*/;
final native CssState getCssState() /*-{
if (this.mode == "css") {
return this.localState;
} else {
return null;
}
}-*/;
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/codemirror2/Parser.java | client/src/main/java/com/google/collide/codemirror2/Parser.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.codemirror2;
import com.google.collide.json.shared.JsonArray;
/**
* Interface that represents CodeMirror parser.
*/
public interface Parser {
/**
* @return {@code true} if {@link #indent} is supported by this parser
*/
boolean hasSmartIndent();
/**
* @return syntax type (language) served by this parser
*/
SyntaxType getSyntaxType();
/**
* @param stateAbove parser state before current line
* @param text left-trimmed content of the line to be indented
* @return proposed number of spaces before the text
*/
int indent(State stateAbove, String text);
/**
* @return newly constructed "before the first line" state
*/
State defaultState();
/**
* Consumes characters from input, updates state
* and pushes recognized token to output.
*/
void parseNext(Stream stream, State parserState, JsonArray<Token> tokens);
/**
* Wraps text in JS object used by native parser.
*/
Stream createStream(String text);
/**
* Extracts the name (mode) from the given {@link State}.
*/
String getName(State state);
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/codemirror2/XmlContext.java | client/src/main/java/com/google/collide/codemirror2/XmlContext.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.codemirror2;
import com.google.gwt.core.client.JavaScriptObject;
/**
* Object that represents xml-state context.
*
*/
public class XmlContext extends JavaScriptObject {
protected XmlContext() {
}
public final native String getTagName() /*-{
return this.tagName;
}-*/;
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/codemirror2/TokenType.java | client/src/main/java/com/google/collide/codemirror2/TokenType.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.codemirror2;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.shared.util.JsonCollections;
import com.google.common.base.Preconditions;
/**
* Enumeration of javascript and python style tokens returned from
* {@link Token#getStyle()}.
*/
public enum TokenType {
ATOM("atom"),
ATTRIBUTE("attribute"),
BUILTIN("builtin"),
COMMENT("comment"),
DEF("def"),
ERROR("error"),
KEYWORD("keyword"),
META("meta"),
NUMBER("number"),
OPERATOR("operator"),
PROPERTY("property"),
STRING("string"),
/**
* RegExp in JS.
*
* <p>NB: Currently not generated by other parsers we use.
*/
REGEXP("string-2"),
TAG("tag"),
VARIABLE("variable"),
VARIABLE2("variable-2"),
WORD("word"),
// Artificial values
NEWLINE("newline"),
// "nil" is a workaround - getting null from map works like getting "null".
NULL("nil"),
WHITESPACE("whitespace");
private final String typeName;
TokenType(String typeName) {
this.typeName = typeName;
}
public String getTypeName() {
return typeName;
}
private static JsonStringMap<TokenType> typesMap;
private static JsonStringMap<TokenType> getTypesMap() {
if (typesMap == null) {
JsonStringMap<TokenType> temp = JsonCollections.createMap();
TokenType[] types = TokenType.values();
for (int i = 0, l = types.length; i < l; i++) {
TokenType type = types[i];
temp.put(type.getTypeName(), type);
}
typesMap = temp;
}
return typesMap;
}
static TokenType resolveTokenType(String cmTokenType, String tokenValue) {
TokenType type = getTypesMap().get(cmTokenType);
Preconditions.checkArgument(cmTokenType == null || type != null, cmTokenType);
if (type == null) {
if (("\n").equals(tokenValue)) {
type = TokenType.NEWLINE;
} else if (tokenValue.trim().length() == 0) {
type = TokenType.WHITESPACE;
} else {
type = TokenType.NULL;
}
}
return type;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/dtogen/client/RoutableDtoClientImpl.java | client/src/main/java/com/google/collide/dtogen/client/RoutableDtoClientImpl.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.client;
import com.google.collide.dtogen.shared.RoutableDto;
import com.google.collide.json.client.Jso;
/**
* Client side base class for all DTO payload implementations.
*
*/
public abstract class RoutableDtoClientImpl extends Jso implements RoutableDto {
// To work around devmode bug where static field references on the interface
// implemented by this SingleJsoImpl, blow up.
@SuppressWarnings("unused")
private static final String TYPE_FIELD = RoutableDto.TYPE_FIELD;
@SuppressWarnings("unused")
private static final int NON_ROUTABLE_TYPE = RoutableDto.NON_ROUTABLE_TYPE;
protected RoutableDtoClientImpl() {
}
/**
* @return the type of the JsonMessage so the client knows how to route it.
*/
public final native int getType() /*-{
return this[@com.google.collide.dtogen.client.RoutableDtoClientImpl::TYPE_FIELD] ||
@com.google.collide.dtogen.client.RoutableDtoClientImpl::NON_ROUTABLE_TYPE;
}-*/;
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/ExceptionHandler.java | client/src/main/java/com/google/collide/client/ExceptionHandler.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.client;
import com.google.collide.client.communication.FrontendApi;
import com.google.collide.client.communication.FrontendApi.ApiCallback;
import com.google.collide.client.communication.MessageFilter;
import com.google.collide.client.communication.MessageFilter.MessageRecipient;
import com.google.collide.client.history.HistoryUtils;
import com.google.collide.client.history.HistoryUtils.SetHistoryListener;
import com.google.collide.client.history.HistoryUtils.ValueChangeListener;
import com.google.collide.client.status.StatusManager;
import com.google.collide.client.status.StatusMessage;
import com.google.collide.client.status.StatusMessage.MessageType;
import com.google.collide.client.util.ExceptionUtils;
import com.google.collide.client.util.logging.Log;
import com.google.collide.dto.LogFatalRecordResponse;
import com.google.collide.dto.RoutingTypes;
import com.google.collide.dto.ServerError;
import com.google.collide.dto.ServerError.FailureReason;
import com.google.collide.dto.StackTraceElementDto;
import com.google.collide.dto.ThrowableDto;
import com.google.collide.dto.client.DtoClientImpls.LogFatalRecordImpl;
import com.google.collide.dto.client.DtoClientImpls.StackTraceElementDtoImpl;
import com.google.collide.dto.client.DtoClientImpls.ThrowableDtoImpl;
import com.google.collide.json.client.JsoArray;
import com.google.collide.shared.util.StringUtils;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.GWT.UncaughtExceptionHandler;
import elemental.client.Browser;
/**
* The global {@link UncaughtExceptionHandler} for Collide. In addition to
* catching uncaught client exceptions, this handler is also responsible for
* notifying the user of server to client errors.
*/
public class ExceptionHandler implements UncaughtExceptionHandler {
private static final String FATAL_MESSAGE =
"Hoist with our own petard. Something broke! We promise that if you reload Collide"
+ " all will be set right :).";
/**
* Record recent history change events (up to some finite maximum) to assist
* failure forensics.
*
*/
private static class HistoryListener implements SetHistoryListener, ValueChangeListener {
private static final int MAX_HISTORY_ENTRIES = 10;
private final JsoArray<String> historyBuffer = JsoArray.create();
private void addHistoryString(String historyString) {
historyBuffer.add(historyString);
if (historyBuffer.size() > MAX_HISTORY_ENTRIES) {
historyBuffer.remove(0);
}
}
@Override
public void onHistorySet(String historyString) {
addHistoryString(historyString);
}
@Override
public void onValueChanged(String historyString) {
addHistoryString(historyString);
}
/**
* Retrieve any stored history entries in descending chronological order
* (most recent first).
*/
public JsoArray<String> getRecentHistory() {
JsoArray<String> ret = historyBuffer.copy();
ret.reverse();
return ret;
}
}
private final HistoryListener historyListener;
private final MessageRecipient<ServerError> serverErrorReceiver =
new MessageRecipient<ServerError>() {
private StatusMessage serverError = null;
@Override
public void onMessageReceived(ServerError message) {
Log.error(getClass(), "Server Error #" + message.getFailureReason() + ": "
+ message.getDetails());
if (serverError != null) {
serverError.cancel();
}
// Authorization errors are handled within the app.
if (message.getFailureReason() != FailureReason.UNAUTHORIZED) {
serverError =
new StatusMessage(statusManager, MessageType.ERROR,
"The server encountered an error (#" + message.getFailureReason() + ")");
serverError.setDismissable(true);
serverError.addAction(StatusMessage.RELOAD_ACTION);
serverError.fire();
}
}
};
private final FrontendApi frontendApi;
private final StatusManager statusManager;
public ExceptionHandler(
MessageFilter messageFilter, FrontendApi frontendApi, StatusManager statusManager) {
this.frontendApi = frontendApi;
this.statusManager = statusManager;
messageFilter.registerMessageRecipient(RoutingTypes.SERVERERROR, serverErrorReceiver);
this.historyListener = new HistoryListener();
HistoryUtils.addSetHistoryListener(historyListener);
HistoryUtils.addValueChangeListener(historyListener);
}
@Override
public void onUncaughtException(Throwable e) {
Log.error(getClass(), e.toString(), e);
final Throwable exception = e;
final JsoArray<String> recentHistory = historyListener.getRecentHistory();
final String currentWindowLocation = Browser.getWindow().getLocation().getHref();
ThrowableDtoImpl throwableDto = getThrowableAsDto(e);
LogFatalRecordImpl logRecord = LogFatalRecordImpl
.make()
.setMessage("Client exception at: " + Browser.getWindow().getLocation().getHref())
.setThrowable(throwableDto)
.setRecentHistory(recentHistory)
.setPermutationStrongName(GWT.getPermutationStrongName());
frontendApi.LOG_REMOTE.send(logRecord, new ApiCallback<LogFatalRecordResponse>() {
@Override
public void onMessageReceived(final LogFatalRecordResponse message) {
StatusMessage msg = new StatusMessage(statusManager, MessageType.FATAL, FATAL_MESSAGE);
msg.addAction(StatusMessage.FEEDBACK_ACTION);
msg.addAction(StatusMessage.RELOAD_ACTION);
String stackTrace;
if (!StringUtils.isNullOrEmpty(message.getStackTrace())) {
stackTrace = message.getStackTrace();
} else {
stackTrace = ExceptionUtils.getStackTraceAsString(exception);
}
msg.setLongText(calculateLongText(stackTrace));
msg.fire();
}
private String calculateLongText(String stackTrace) {
return "Client exception at " + currentWindowLocation + "\n\nRecent history:\n\t"
+ recentHistory.join("\n\t") + "\n\n" + stackTrace;
}
@Override
public void onFail(FailureReason reason) {
StatusMessage msg = new StatusMessage(statusManager, MessageType.FATAL, FATAL_MESSAGE);
msg.addAction(StatusMessage.FEEDBACK_ACTION);
msg.addAction(StatusMessage.RELOAD_ACTION);
msg.setLongText(calculateLongText(ExceptionUtils.getStackTraceAsString(exception)));
msg.fire();
}
});
}
/**
* Serialize a {@link Throwable} as a {@link ThrowableDto}.
*/
private static ThrowableDtoImpl getThrowableAsDto(Throwable e) {
ThrowableDtoImpl ret = ThrowableDtoImpl.make();
ThrowableDtoImpl currentDto = ret;
Throwable currentCause = e;
for (int causeCounter = 0; causeCounter < ExceptionUtils.MAX_CAUSE && currentCause != null;
causeCounter++) {
currentDto.setClassName(currentCause.getClass().getName());
currentDto.setMessage(currentCause.getMessage());
JsoArray<StackTraceElementDto> currentStackTrace = JsoArray.create();
StackTraceElement[] stackElems = currentCause.getStackTrace();
if (stackElems != null) {
for (int i = 0; i < stackElems.length; ++i) {
StackTraceElement stackElem = stackElems[i];
currentStackTrace.add(StackTraceElementDtoImpl
.make()
.setClassName(stackElem.getClassName())
.setFileName(stackElem.getFileName())
.setMethodName(stackElem.getMethodName())
.setLineNumber(stackElem.getLineNumber()));
}
currentDto.setStackTrace(currentStackTrace);
}
currentCause = currentCause.getCause();
if (currentCause != null) {
ThrowableDtoImpl nextDto = ThrowableDtoImpl.make();
currentDto.setCause(nextDto);
currentDto = nextDto;
}
}
return ret;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/AppContext.java | client/src/main/java/com/google/collide/client/AppContext.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.client;
import com.google.collide.client.communication.FrontendApi;
import com.google.collide.client.communication.MessageFilter;
import com.google.collide.client.communication.PushChannel;
import com.google.collide.client.editor.EditorContext;
import com.google.collide.client.search.awesomebox.AwesomeBoxModel;
import com.google.collide.client.search.awesomebox.host.AwesomeBoxComponentHostModel;
import com.google.collide.client.status.StatusManager;
import com.google.collide.client.util.UserActivityManager;
import com.google.collide.client.util.WindowUnloadingController;
import com.google.collide.client.util.dom.eventcapture.KeyBindings;
import com.google.common.annotations.VisibleForTesting;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.GWT.UncaughtExceptionHandler;
/**
* Application context object that exposes getters for our PushChannel and our Event Bus.
*
*/
public class AppContext implements EditorContext<Resources> {
// This is static final for now, but could be more flexible later.
public static final String GWT_ROOT = "gwt_root";
public static AppContext create() {
return new AppContext();
}
private final KeyBindings keyBindings;
/**
* Object for making calls to the frontend api.
*/
private final FrontendApi frontendApi;
private final Resources resources = GWT.create(Resources.class);
/**
* For directly handling messages/data sent to the client from the frontend.
*/
private final MessageFilter messageFilter;
private final StatusManager statusManager;
private final UncaughtExceptionHandler uncaughtExceptionHandler;
private final AwesomeBoxModel awesomeBoxModel;
private final AwesomeBoxComponentHostModel awesomeBoxComponentHostModel;
private final UserActivityManager userActivityManager;
private final WindowUnloadingController windowUnloadingController;
private final PushChannel pushChannel;
@VisibleForTesting
public AppContext() {
// Things that depend on nothing
this.keyBindings = new KeyBindings();
this.statusManager = new StatusManager();
this.messageFilter = new MessageFilter();
this.awesomeBoxModel = new AwesomeBoxModel();
this.awesomeBoxComponentHostModel = new AwesomeBoxComponentHostModel();
this.userActivityManager = new UserActivityManager();
this.windowUnloadingController = new WindowUnloadingController();
// Things that depend on message filter/frontendApi/statusManager
this.pushChannel = PushChannel.create(messageFilter, statusManager);
this.frontendApi = FrontendApi.create(pushChannel, statusManager);
this.uncaughtExceptionHandler = new ExceptionHandler(messageFilter, frontendApi, statusManager);
}
public KeyBindings getKeyBindings() {
return keyBindings;
}
public AwesomeBoxModel getAwesomeBoxModel() {
return awesomeBoxModel;
}
public AwesomeBoxComponentHostModel getAwesomeBoxComponentHostModel() {
return awesomeBoxComponentHostModel;
}
public UserActivityManager getUserActivityManager() {
return userActivityManager;
}
/**
* @return the frontendRequester
*/
public FrontendApi getFrontendApi() {
return frontendApi;
}
/**
* @return the messageFilter
*/
public MessageFilter getMessageFilter() {
return messageFilter;
}
/**
* @return the push channel API
*/
public PushChannel getPushChannel() {
return pushChannel;
}
/**
* @return the resources
*/
public Resources getResources() {
return resources;
}
public StatusManager getStatusManager() {
return statusManager;
}
/**
* @return the uncaught exception handler for the app.
*/
public UncaughtExceptionHandler getUncaughtExceptionHandler() {
return uncaughtExceptionHandler;
}
/**
* @return the {@link WindowUnloadingController} for the app.
*/
public WindowUnloadingController getWindowUnloadingController() {
return windowUnloadingController;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/CollideBootstrap.java | client/src/main/java/com/google/collide/client/CollideBootstrap.java | package com.google.collide.client;
import collide.client.util.Elements;
import com.google.collide.client.bootstrap.BootstrapSession;
import com.google.collide.client.util.ClientImplementationsInjector;
import com.google.collide.client.xhrmonitor.XhrWarden;
import com.google.collide.codemirror2.CodeMirror2;
import elemental.html.DivElement;
import xapi.fu.Lazy;
import xapi.util.api.SuccessHandler;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.StyleInjector;
import com.google.gwt.user.client.Window;
public class CollideBootstrap extends Lazy<AppContext> {
private CollideBootstrap() {
super(() -> {
if (Elements.getElementById("gwt_root") == null) {
DivElement el = Elements.createDivElement();
el.setId("gwt_root");
Elements.getBody().appendChild(el);
}
ClientImplementationsInjector.inject();
final AppContext appContext = AppContext.create();
GWT.setUncaughtExceptionHandler(appContext.getUncaughtExceptionHandler());
XhrWarden.watch();
Resources resources = appContext.getResources();
// TODO: Figure out why when we use the + operator to concat,
// these Strings don't at compile time converge to a single String literal.
// In theory they should. For now we use a StringBuilder.
// TODO: remove alllll this ugly w/ generated code...
// Make sure you call getText() on your CssResource!
StringBuilder styleBuilder = new StringBuilder();
styleBuilder.append(resources.appCss().getText());
styleBuilder.append(resources.baseCss().getText());
styleBuilder.append(resources.workspaceHeaderCss().getText());
styleBuilder.append(resources.editorToolBarCss().getText());
styleBuilder.append(resources.defaultSimpleListCss().getText());
styleBuilder.append(resources.workspaceShellCss().getText());
styleBuilder.append(resources.workspaceEditorCss().getText());
styleBuilder.append(resources.workspaceEditorBufferCss().getText());
styleBuilder.append(resources.workspaceEditorCursorCss().getText());
styleBuilder.append(resources.workspaceEditorConsoleViewCss().getText());
styleBuilder.append(resources.workspaceEditorDebuggingModelCss().getText());
styleBuilder.append(resources.workspaceEditorDebuggingSidebarCss().getText());
styleBuilder.append(resources.workspaceEditorDebuggingSidebarBreakpointsPaneCss().getText());
styleBuilder.append(resources.workspaceEditorDebuggingSidebarCallStackPaneCss().getText());
styleBuilder.append(resources.workspaceEditorDebuggingSidebarControlsPaneCss().getText());
styleBuilder.append(resources.workspaceEditorDebuggingSidebarHeaderCss().getText());
styleBuilder.append(resources.workspaceEditorDebuggingSidebarNoApiPaneCss().getText());
styleBuilder.append(resources.workspaceEditorDebuggingSidebarScopeVariablesPaneCss().getText());
styleBuilder.append(resources.workspaceEditorDomInspectorCss().getText());
styleBuilder.append(resources.workspaceEditorDebuggingSidebarWatchExpressionsPaneCss().getText());
styleBuilder.append(resources.remoteObjectTreeCss().getText());
styleBuilder.append(resources.remoteObjectNodeRendererCss().getText());
styleBuilder.append(resources.editorDiffContainerCss().getText());
styleBuilder.append(resources.evaluationPopupControllerCss().getText());
styleBuilder.append(resources.goToDefinitionCss().getText());
styleBuilder.append(resources.treeCss().getText());
styleBuilder.append(resources.workspaceNavigationCss().getText());
styleBuilder.append(resources.workspaceNavigationFileTreeSectionCss().getText());
styleBuilder.append(resources.workspaceNavigationShareWorkspacePaneCss().getText());
styleBuilder.append(resources.workspaceNavigationToolBarCss().getText());
styleBuilder.append(resources.workspaceNavigationFileTreeNodeRendererCss().getText());
styleBuilder.append(resources.workspaceNavigationOutlineNodeRendererCss().getText());
styleBuilder.append(resources.workspaceNavigationParticipantListCss().getText());
styleBuilder.append(resources.searchContainerCss().getText());
styleBuilder.append(resources.statusPresenterCss().getText());
styleBuilder.append(resources.noFileSelectedPanelCss().getText());
styleBuilder.append(resources.diffRendererCss().getText());
styleBuilder.append(resources.deltaInfoBarCss().getText());
styleBuilder.append(resources.codePerspectiveCss().getText());
styleBuilder.append(resources.unauthorizedUserCss().getText());
styleBuilder.append(resources.syntaxHighlighterRendererCss().getText());
styleBuilder.append(resources.lineNumberRendererCss().getText());
styleBuilder.append(resources.uneditableDisplayCss().getText());
styleBuilder.append(resources.editorSelectionLineRendererCss().getText());
styleBuilder.append(resources.fileHistoryCss().getText());
styleBuilder.append(resources.timelineCss().getText());
styleBuilder.append(resources.timelineNodeCss().getText());
styleBuilder.append(resources.panelCss().getText());
styleBuilder.append(resources.popupCss().getText());
styleBuilder.append(resources.tooltipCss().getText());
styleBuilder.append(resources.sliderCss().getText());
styleBuilder.append(resources.editableContentAreaCss().getText());
styleBuilder.append(resources.workspaceLocationBreadcrumbsCss().getText());
styleBuilder.append(resources.awesomeBoxCss().getText());
styleBuilder.append(resources.awesomeBoxSectionCss().getText());
styleBuilder.append(resources.centerPanelCss().getText());
styleBuilder.append(resources.autocompleteComponentCss().getText());
styleBuilder.append(resources.runButtonTargetPopupCss().getText());
styleBuilder.append(resources.popupBlockedInstructionalPopupCss().getText());
styleBuilder.append(resources.dropdownWidgetsCss().getText());
styleBuilder.append(resources.parenMatchHighlighterCss().getText());
styleBuilder.append(resources.awesomeBoxHostCss().getText());
styleBuilder.append(resources.awesomeBoxComponentCss().getText());
styleBuilder.append(resources.coachmarkCss().getText());
styleBuilder.append(resources.sidebarListCss().getText());
/* workspaceNavigationSectionCss, animationController, and resizeControllerCss must come last because they
* overwrite the CSS properties from previous CSS rules. */
styleBuilder.append(resources.workspaceNavigationSectionCss().getText());
styleBuilder.append(resources.resizeControllerCss().getText());
StyleInjector.inject(styleBuilder.toString());
Elements.injectJs(CodeMirror2.getJs(resources));
return appContext;
}
);
}
private static final CollideBootstrap bootstrap = new CollideBootstrap();
public static void start(SuccessHandler<AppContext> successHandler) {
// If we do not have a valid Client ID, we need to popup a login page.
if (BootstrapSession.getBootstrapSession().getActiveClientId() == null) {
if (Window.Location.getPath().startsWith("/collide"))
Window.Location.assign("/collide/static/login.html");
else
Window.Location.assign("/static/login.html");
return;
}
successHandler.onSuccess(bootstrap.out1());
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.