code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* Copyright (C) 2009 The Guava Authors
*
* 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.common.net;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.escape.Escaper;
import com.google.common.net.PercentEscaper;
/**
* A factory for {@code Escaper} instances suitable for escaping strings so they
* can be safely included in URIs or particular sections of URIs.
*
* <p>For more information on URI escaping, see
* <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>.
*
* @author David Beaumont
* @since 11.0
*/
@Beta
@GwtCompatible
public final class UriEscapers {
private UriEscapers() { }
// For each xxxEscaper() method, please add links to external reference pages
// that are considered authoritative for the behavior of that escaper.
// TODO(user): Remove the 'plusForSpace' boolean in favor of an enum.
// As 'plusForSpace' is mostly not the right thing to use, we should consider
// having an enum to give it an explicit name and associated documentation.
/**
* Returns an {@link Escaper} instance that escapes Java chars so they can be
* safely included in URIs. For details on escaping URIs, see section 2.4 of
* <a href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a>.
*
* <p>When encoding a String, the following rules apply:
* <ul>
* <li>The alphanumeric characters "a" through "z", "A" through "Z" and "0"
* through "9" remain the same.
* <li>The special characters ".", "-", "*", and "_" remain the same.
* <li>The space character " " is converted into a plus sign "+".
* <li>All other characters are converted into one or more bytes using UTF-8
* encoding and each byte is then represented by the 3-character string
* "%XY", where "XY" is the two-digit, uppercase, hexadecimal
* representation of the byte value.
* <ul>
*
* <p><b>Note</b>: Unlike other escapers, URI escapers produce uppercase
* hexadecimal sequences. From <a href="http://www.ietf.org/rfc/rfc3986.txt">
* RFC 3986</a>:<br>
* <i>"URI producers and normalizers should use uppercase hexadecimal digits
* for all percent-encodings."</i>
*
*
* <p>This method is equivalent to {@code uriEscaper(true)}.
*/
public static Escaper uriEscaper() {
return uriEscaper(true);
}
/**
* Returns a {@link Escaper} instance that escapes Java characters so they can
* be safely included in URIs. For details on escaping URIs, see section 2.4
* of <a href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a>.
*
* <p>When encoding a String, the following rules apply:
* <ul>
* <li>The alphanumeric characters "a" through "z", "A" through "Z" and "0"
* through "9" remain the same.
* <li>The special characters ".", "-", "*", and "_" remain the same.
* <li>If {@code plusForSpace} was specified, the space character " " is
* converted into a plus sign "+". Otherwise it is converted into "%20".
* <li>All other characters are converted into one or more bytes using UTF-8
* encoding and each byte is then represented by the 3-character string
* "%XY", where "XY" is the two-digit, uppercase, hexadecimal
* representation of the byte value.
* </ul>
*
* <p>The need to use {@code plusForSpace} is limited to a small set of use
* cases relating to URL encoded forms and should be avoided otherwise. For
* more information on when it may be appropriate to use {@code plusForSpace},
* see <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1">
* "Forms in HTML documents".</a>
*
* <p><b>Note</b>: Unlike other escapers, URI escapers produce uppercase
* hexadecimal sequences. From <a href="http://www.ietf.org/rfc/rfc3986.txt">
* RFC 3986</a>:<br>
* <i>"URI producers and normalizers should use uppercase hexadecimal digits
* for all percent-encodings."</i>
*
* @param plusForSpace if {@code true} space is escaped to {@code +} otherwise
* it is escaped to {@code %20}. Although common, the escaping of
* spaces as plus signs has a very ambiguous status in the relevant
* specifications. You should prefer {@code %20} unless you are doing
* exact character-by-character comparisons of URLs and backwards
* compatibility requires you to use plus signs.
*
* @see #uriEscaper()
*/
public static Escaper uriEscaper(boolean plusForSpace) {
return plusForSpace ? URI_ESCAPER : URI_ESCAPER_NO_PLUS;
}
/**
* A string of safe characters that mimics the behavior of
* {@link java.net.URLEncoder}.
*/
public static final String URI_SAFECHARS_JAVA = "-_.*";
private static final Escaper URI_ESCAPER =
new PercentEscaper(URI_SAFECHARS_JAVA, true);
private static final Escaper URI_ESCAPER_NO_PLUS =
new PercentEscaper(URI_SAFECHARS_JAVA, false);
/**
* Returns an {@link Escaper} instance that escapes Java chars so they can be
* safely included in URI path segments. For details on escaping URIs, see
* section 2.4 of <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>.
*
* <p>When encoding a String, the following rules apply:
* <ul>
* <li>The alphanumeric characters "a" through "z", "A" through "Z" and "0"
* through "9" remain the same.
* <li>The unreserved characters ".", "-", "~", and "_" remain the same.
* <li>The general delimiters "@" and ":" remain the same.
* <li>The subdelimiters "!", "$", "&", "'", "(", ")", "*", ",", ";",
* and "=" remain the same.
* <li>The space character " " is converted into %20.
* <li>All other characters are converted into one or more bytes using UTF-8
* encoding and each byte is then represented by the 3-character string
* "%XY", where "XY" is the two-digit, uppercase, hexadecimal
* representation of the byte value.
* </ul>
*
* <p><b>Note</b>: Unlike other escapers, URI escapers produce uppercase
* hexadecimal sequences. From <a href="http://www.ietf.org/rfc/rfc3986.txt">
* RFC 3986</a>:<br>
* <i>"URI producers and normalizers should use uppercase hexadecimal digits
* for all percent-encodings."</i>
*
* <p>This method differs from {@link #uriPathEscaperRfcCompliant} by
* escaping "+" characters into "%2D".
*/
public static Escaper uriPathEscaper() {
return URI_PATH_ESCAPER;
}
/**
* Returns an {@link Escaper} instance that escapes Java chars so they can be
* safely included in URI path segments. For details on escaping URIs, see
* section 2.4 of <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>.
*
* <p>When encoding a String, the following rules apply:
* <ul>
* <li>The alphanumeric characters "a" through "z", "A" through "Z" and "0"
* through "9" remain the same.
* <li>The unreserved characters ".", "-", "~", and "_" remain the same.
* <li>The general delimiters "@" and ":" remain the same.
* <li>The subdelimiters "!", "$", "&", "'", "(", ")", "*", "+", ",", ";",
* and "=" remain the same.
* <li>If {@code escapePlus} was specified, the plus character "+" is
* converted into "%2B", otherwise it remains the same.
* <li>The space character " " is converted into %20.
* <li>All other characters are converted into one or more bytes using UTF-8
* encoding and each byte is then represented by the 3-character string
* "%XY", where "XY" is the two-digit, uppercase, hexadecimal
* representation of the byte value.
* </ul>
*
* <p><b>Note</b>: Unlike other escapers, URI escapers produce uppercase
* hexadecimal sequences. From <a href="http://www.ietf.org/rfc/rfc3986.txt">
* RFC 3986</a>:<br>
* <i>"URI producers and normalizers should use uppercase hexadecimal digits
* for all percent-encodings."</i>
*
* <p>This method differs from {@link #uriPathEscaper} by not escaping
* "+" characters, treating them the same as the other sub-delimiters
* described by RFC 3986. Note that the version that does escape "+" characters
* is in common use and therefore the use of this method should be done
* carefully to avoid compatibility problems, especially when comparing URLs.
*/
public static Escaper uriPathEscaperRfcCompliant() {
return URI_PATH_ESCAPER_RFC_COMPLIANT;
}
/**
* The set of path characters as defined by RFC 3986 excluding the plus
* character {@code '+'}. This set of characters is used as the basis for
* most of the 'safe' strings for URIs.
*/
public static final String URI_SAFECHARS_PATH =
"-._~" + // Unreserved characters.
"!$'()*,;&=" + // The subdelim characters (excluding '+').
"@:"; // The gendelim characters permitted in paths.
private static final Escaper URI_PATH_ESCAPER =
new PercentEscaper(URI_SAFECHARS_PATH, false);
private static final Escaper URI_PATH_ESCAPER_RFC_COMPLIANT =
new PercentEscaper(URI_SAFECHARS_PATH + "+", false);
/**
* Returns an {@link Escaper} instance that escapes Java chars so they can be
* safely included in URI query string segments. When the query string
* consists of a sequence of name=value pairs separated by &, the names
* and values should be individually encoded. If you escape an entire query
* string in one pass with this escaper, then the "=" and "&" characters
* used as separators will also be escaped.
*
* <p>This escaper is also suitable for escaping fragment identifiers.
*
* <p>For details on escaping URIs, see
* section 2.4 of <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>.
*
* <p>When encoding a String, the following rules apply:
* <ul>
* <li>The alphanumeric characters "a" through "z", "A" through "Z" and "0"
* through "9" remain the same.
* <li>The unreserved characters ".", "-", "~", and "_" remain the same.
* <li>The general delimiters "@" and ":" remain the same.
* <li>The path delimiters "/" and "?" remain the same.
* <li>The subdelimiters "!", "$", "'", "(", ")", "*", ",", and ";",
* remain the same.
* <li>The space character " " is converted into %20.
* <li>The equals sign "=" is converted into %3D.
* <li>The ampersand "&" is converted into %26.
* <li>All other characters are converted into one or more bytes using UTF-8
* encoding and each byte is then represented by the 3-character string
* "%XY", where "XY" is the two-digit, uppercase, hexadecimal
* representation of the byte value.
* </ul>
*
* <p>The need to use {@code plusForSpace} is limited to a small set of use
* cases relating to URL encoded forms and should be avoided otherwise. For
* more information on when it may be appropriate to use {@code plusForSpace},
* see <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1">
* "Forms in HTML documents".</a>
*
* <p><b>Note</b>: Unlike other escapers, URI escapers produce uppercase
* hexadecimal sequences. From <a href="http://www.ietf.org/rfc/rfc3986.txt">
* RFC 3986</a>:<br>
* <i>"URI producers and normalizers should use uppercase hexadecimal digits
* for all percent-encodings."</i>
*
* @param plusForSpace if {@code true} space is escaped to {@code +} otherwise
* it is escaped to {@code %20}. Although common, the escaping of
* spaces as plus signs has a very ambiguous status in the relevant
* specifications. You should prefer {@code %20} unless you are doing
* exact character-by-character comparisons of URLs and backwards
* compatibility requires you to use plus signs.
*/
public static Escaper uriQueryStringEscaper(boolean plusForSpace) {
return plusForSpace ? QUERY_STRING_ESCAPER : QUERY_STRING_ESCAPER_NO_PLUS;
}
/**
* A string of characters that do not need to be escaped when used in the
* key/value arguments that make up the query parameters of an HTTP URL. Note
* that some of these characters do need to be escaped when used in other
* parts of the URI.
*/
public static final String URI_SAFECHARS_QUERY_STRING =
"-._~" + // Unreserved characters
"!$'()*,;" + // The subdelim characters (excluding '+', '&' and '=').
"@:/?"; // The gendelim characters permitted in query parameters.
private static final Escaper QUERY_STRING_ESCAPER =
new PercentEscaper(URI_SAFECHARS_QUERY_STRING, true);
private static final Escaper QUERY_STRING_ESCAPER_NO_PLUS =
new PercentEscaper(URI_SAFECHARS_QUERY_STRING, false);
/**
* Returns an {@link Escaper} instance which ensures that any invalid Unicode
* code points in a URI are correctly percent escaped. This escaper is
* suitable for applying additional escaping to partially escaped URIs and
* <em>will not</em> correctly escape data during the creation of a URI.
*
* <p>This escaper is special in that it <em>does not</em> escape the
* {@code %} character and as such does not have a well defined inverse.
* It assumes that a minimal amount of percent-escaping has already been
* applied to the input, at least ensuring that {@code %} itself is escaped.
*
* <p>For details on escaping URIs, see
* section 2.4 of <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>.
*
* <p>When encoding a String, the following rules apply:
* <ul>
* <li>The alphanumeric characters "a" through "z", "A" through "Z" and "0"
* through "9" remain the same.
* <li>The unreserved characters ".", "-", "~", and "_" remain the same.
* <li>The general delimiters ":", "/", "?", "#", "[", "]" and "@" remain the
* same.
* <li>The subdelimiters "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", and
* "=" remain the same.
* <li><em>The percent character "%" remains the same.</em>
* <li>All other characters are converted into one or more bytes using UTF-8
* encoding and each byte is then represented by the 3-character string
* "%XY", where "XY" is the two-digit, uppercase, hexadecimal
* representation of the byte value.
* </ul>
*
* <p>This escaper is useful in cases where we have a partially escaped (but
* not ambiguous) URI such as:
* <pre>{@code http://example.com/foo|bar%26baz}</pre>
* If we re-escape the string representation of the complete URI we get:
* <pre>{@code http://example.com/foo%7Cbar%26baz}</pre>
*
* <p>Note that this escaper only canonicalizes with respect to percent
* escaping and in general <em>will not</em> make the string representations
* of URIs comparable in a meaningful way.
*
* <p>This escaper is idempotent and escaping an already validly escaped URI
* will have no effect.
*/
public static Escaper canonicalizingEscaper() {
return CANONICALIZING_ESCAPER;
}
private static final String ALL_VALID_URI_CHARS =
"-._~" + // Unreserved characters.
":/?#[]@" + // Gendelim chars.
"!$&'()*+,;=" + // Subdelim chars.
"%"; // The percent character itself!
private static final Escaper CANONICALIZING_ESCAPER =
new PercentEscaper(ALL_VALID_URI_CHARS, false);
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.client;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.walkaround.slob.shared.ChangeData;
import com.google.walkaround.slob.shared.ClientId;
import org.waveprotocol.wave.client.common.util.JsoView;
/**
* @author danilatos@google.com (Daniel Danilatos)
*/
public final class ChangeDataParser {
private ChangeDataParser() {}
public static ChangeData<JavaScriptObject> fromJson(JsoView jso) {
return new ChangeData<JavaScriptObject>(new ClientId(jso.getString("sid")), jso.getJso("op"));
}
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.client;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import org.waveprotocol.wave.model.operation.OperationPair;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* Simple implementation of main concurrency control logic, independent of
* transport concerns.
*
* <p>
* For efficiency, client ops are also compacted before transforming and before
* sending.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class TransformQueue<M> {
public interface Transformer<M> {
OperationPair<M> transform(M clientOp, M serverOp);
List<M> compact(List<M> clientOps);
}
private final Transformer<M> transformer;
private int revision = -1;
@VisibleForTesting int expectedAckedClientOps = 0;
@VisibleForTesting List<M> serverOps = new LinkedList<M>();
@VisibleForTesting List<M> unackedClientOps = Collections.emptyList();
@VisibleForTesting List<M> queuedClientOps = new LinkedList<M>();
boolean newClientOpSinceTransform = false;
public TransformQueue(Transformer<M> transformer) {
this.transformer = transformer;
}
public void init(int revision) {
Preconditions.checkState(this.revision == -1, "Already at a revision (%s), can't init at %s)",
this.revision, revision);
Preconditions.checkArgument(revision >= 0, "Initial revision must be >= 0, not %s", revision);
this.revision = revision;
}
public void serverOp(int resultingRevision, M serverOp) {
checkRevision(resultingRevision);
Preconditions.checkState(expectedAckedClientOps == 0,
"server op arrived @%s while expecting %s client ops",
resultingRevision, expectedAckedClientOps);
this.revision = resultingRevision;
if (!unackedClientOps.isEmpty()) {
List<M> newUnackedClientOps = new LinkedList<M>();
for (M clientOp : unackedClientOps) {
OperationPair<M> pair = transformer.transform(clientOp, serverOp);
newUnackedClientOps.add(pair.clientOp());
serverOp = pair.serverOp();
}
unackedClientOps = newUnackedClientOps;
}
if (!queuedClientOps.isEmpty()) {
if (newClientOpSinceTransform) {
queuedClientOps = transformer.compact(queuedClientOps);
}
newClientOpSinceTransform = false;
List<M> newQueuedClientOps = new LinkedList<M>();
for (M clientOp : queuedClientOps) {
OperationPair<M> pair = transformer.transform(clientOp, serverOp);
newQueuedClientOps.add(pair.clientOp());
serverOp = pair.serverOp();
}
queuedClientOps = newQueuedClientOps;
}
serverOps.add(serverOp);
}
public void clientOp(M clientOp) {
if (!serverOps.isEmpty()) {
List<M> newServerOps = new LinkedList<M>();
for (M serverOp : serverOps) {
OperationPair<M> pair = transformer.transform(clientOp, serverOp);
newServerOps.add(pair.serverOp());
clientOp = pair.clientOp();
}
serverOps = newServerOps;
}
queuedClientOps.add(clientOp);
newClientOpSinceTransform = true;
}
public boolean expectedAck(int resultingRevision) {
if (expectedAckedClientOps == 0) {
return false;
}
Preconditions.checkArgument(resultingRevision == revision - expectedAckedClientOps + 1,
"bad rev %s, current rev %s, expected remaining %s",
resultingRevision, revision, expectedAckedClientOps);
expectedAckedClientOps--;
return true;
}
/**
* @param resultingRevision
* @return true if all unacked ops are now acked
*/
public boolean ackClientOp(int resultingRevision) {
checkRevision(resultingRevision);
Preconditions.checkState(expectedAckedClientOps == 0,
"must call expectedAck, there are %s expectedAckedClientOps", expectedAckedClientOps);
Preconditions.checkState(!unackedClientOps.isEmpty(),
"%s: unackedClientOps is empty; resultingRevision=%s", this, resultingRevision);
this.revision = resultingRevision;
unackedClientOps.remove(0);
return unackedClientOps.isEmpty();
}
/**
* Pushes the queued client ops into the unacked ops, clearing the queued ops.
* @return see {@link #unackedClientOps()}
*/
public List<M> pushQueuedOpsToUnacked() {
Preconditions.checkState(unackedClientOps.isEmpty(),
"Queue contains unacknowledged operations: %s", unackedClientOps);
unackedClientOps = new LinkedList<M>(transformer.compact(queuedClientOps));
queuedClientOps = new LinkedList<M>();
return unackedClientOps();
}
public List<M> ackOpsIfVersionMatches(int newRevision) {
if (newRevision == revision + unackedClientOps.size()) {
List<M> expectedAckingClientOps = unackedClientOps;
expectedAckedClientOps += expectedAckingClientOps.size();
unackedClientOps = new LinkedList<M>();
revision = newRevision;
return expectedAckingClientOps;
}
return null;
}
/**
* @return the current unacked client ops. Note: the behavior of this list
* after calling mutating methods on the transform queue is undefined.
* This method should be called each time immediately before use.
*/
public List<M> unackedClientOps() {
return Collections.unmodifiableList(unackedClientOps);
}
public int unackedClientOpsCount() {
return unackedClientOps.size();
}
public boolean hasServerOp() {
return !serverOps.isEmpty();
}
public boolean hasUnacknowledgedClientOps() {
return !unackedClientOps.isEmpty();
}
public boolean hasQueuedClientOps() {
return !queuedClientOps.isEmpty();
}
public M peekServerOp() {
Preconditions.checkState(hasServerOp(), "No server ops");
return serverOps.get(0);
}
public M removeServerOp() {
Preconditions.checkState(hasServerOp(), "No server ops");
return serverOps.remove(0);
}
public int revision() {
return revision;
}
private void checkRevision(int resultingRevision) {
Preconditions.checkArgument(resultingRevision >= 1, "New revision %s must be >= 1",
resultingRevision);
Preconditions.checkState(this.revision == resultingRevision - 1,
"Revision mismatch: at %s, received %s", this.revision, resultingRevision);
}
@Override
public String toString() {
return "TQ{ " + revision + "\n s:" + serverOps +
"\n exp: " + expectedAckedClientOps +
"\n u:" + unackedClientOps + "\n q:" + queuedClientOps + "\n}";
}
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.client;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.walkaround.slob.client.TransformQueue.Transformer;
import com.google.walkaround.util.client.log.Logs.Level;
import com.google.walkaround.util.client.log.Logs.Log;
import org.waveprotocol.wave.client.scheduler.Scheduler;
import org.waveprotocol.wave.client.scheduler.TimerService;
import org.waveprotocol.wave.model.util.FuzzingBackOffGenerator;
import java.util.EnumSet;
import java.util.List;
/**
* Service that handles transportation and transforming of client and server
* operations.
*
* @author danilatos@google.com (Daniel Danilatos)
*
* @param <M> Mutation type.
*/
public class GenericOperationChannel<M> {
/**
* Provides a channel for incoming operations.
*/
public interface ReceiveOpChannel<M> {
public interface Listener<M> {
void onMessage(int resultingRevision, String sid, M mutation);
void onError(Throwable e);
}
void connect(int revision, Listener<M> listener);
void disconnect();
}
/**
* Provides a service to send outgoing operations and synchronize the
* concurrent object with the server.
*/
public interface SendOpService<M> {
public interface Callback {
void onSuccess(int appliedRevision);
void onConnectionError(Throwable e);
void onFatalError(Throwable e);
}
/**
* Submit operations at the given revision.
*
* <p>Will be called back with the revision at which the ops were applied.
*/
void submitOperations(int revision, List<M> operations, Callback callback);
/**
* Lightweight request to get the current revision of the object without
* submitting operations (somewhat equivalent to applying no operations).
*
* <p>Useful for synchronizing with the channel for retrying/reconnection.
*/
void requestRevision(Callback callback);
/**
* Called to indicate that the channel is no longer interested in being
* notified via the given callback object, so implementations may optionally
* discard the associated request state and callback. It is safe to do
* nothing with this method.
*
* @param callback
*/
void callbackNotNeeded(Callback callback);
}
/**
* Notifies when operations and acknowledgments come in. The values passed to
* the methods can be used to reconstruct the exact server history.
*
* <p>WARNING: The server history ops cannot be applied to local client
* state, because they have not been transformed properly. Server history
* ops are for other uses. To get the server ops to apply locally, use
* {@link GenericOperationChannel#receive()}
*/
public interface Listener<M> {
/**
* A remote op has been received. Do not use the parameter to apply to local
* state, instead use {@link GenericOperationChannel#receive()}.
*
* @param serverHistoryOp the operation as it appears in the server history
* (do not apply this to local state).
*/
void onRemoteOp(M serverHistoryOp);
/**
* A local op is acknowledged as applied at this point in the server history
* op stream.
*
* @param serverHistoryOp the operation as it appears in the server history,
* not necessarily as it was when passed into the channel.
* @param clean true if the channel is now clean.
*/
void onAck(M serverHistoryOp, boolean clean);
/**
* Called when some unrecoverable problem occurs.
*/
void onError(Throwable e);
}
private final Scheduler.Task maybeSendTask = new Scheduler.Task() {
@Override public void execute() {
maybeSend();
}
};
private final Scheduler.Task delayedResyncTask = new Scheduler.Task() {
@Override public void execute() {
doResync();
}
};
private final ReceiveOpChannel.Listener<M> receiveListener = new ReceiveOpChannel.Listener<M>() {
@Override public void onMessage(int resultingRevision, String sid, M operation) {
if (!isConnected()) {
return;
}
logger.log(Level.DEBUG, "my sid=", sessionId, ", incoming sid=", sid);
if (sessionId.equals(sid)) {
onAckOwnOperation(resultingRevision, operation);
} else {
onIncomingOperation(resultingRevision, operation);
}
maybeSynced();
}
@Override public void onError(Throwable e) {
if (!isConnected()) {
return;
}
listener.onError(e);
}
};
/**
* To reduce the risk of the channel behaving unpredictably due to poor
* external implementations, we handle discarding callbacks internally and
* merely hint to the service that it may be discarded.
*/
abstract class DiscardableCallback implements SendOpService.Callback {
private boolean discarded = false;
void discard() {
if (discarded) {
return;
}
discarded = true;
submitService.callbackNotNeeded(this);
}
@Override
public void onConnectionError(Throwable e) {
if (!isConnected()) {
return;
}
if (discarded) {
logger.log(Level.WARNING, "Ignoring failure, ", e);
return;
}
discarded = true;
logger.log(Level.WARNING, "Retryable failure, will resync.", e);
delayResync();
}
@Override
public void onSuccess(int appliedRevision) {
if (!isConnected()) {
return;
}
if (discarded) {
logger.log(Level.INFO, "Ignoring success @", appliedRevision);
return;
}
discarded = true;
success(appliedRevision);
}
@Override
public final void onFatalError(Throwable e) {
fail(e);
}
abstract void success(int appliedRevision);
}
enum State {
/**
* Cannot send ops in this state. All states can transition here if either
* explicitly requested, or if there is a permanent failure.
*/
UNINITIALISED,
/**
* No unacked ops. There may be queued ops though.
*/
ALL_ACKED,
/**
* Waiting for an ack for sent ops. Will transition back to ALL_ACKED if
* successful, or to DELAY_RESYNC if there is a retryable failure.
*/
WAITING_ACK,
/**
* Waiting to attempt a resync/reconnect (delay can be large due to
* exponential backoff). Will transition to WAITING_SYNC when the delay is
* up and we send off the version request, or to ALL_ACKED if all ops get
* acked while waiting.
*/
DELAY_RESYNC,
/**
* Waiting for our version sync. If it turns out that all ops get acked down
* the channel in the meantime, we can return to ALL_ACKED. Otherwise, we
* can resend and go to WAITING_ACK. If there is a retryable failure, we
* will go to DELAY_RESYNC
*/
WAITING_SYNC;
private EnumSet<State> to;
static {
UNINITIALISED.transitionsTo(ALL_ACKED);
ALL_ACKED.transitionsTo(WAITING_ACK);
WAITING_ACK.transitionsTo(ALL_ACKED, DELAY_RESYNC);
DELAY_RESYNC.transitionsTo(ALL_ACKED, WAITING_SYNC);
WAITING_SYNC.transitionsTo(ALL_ACKED, WAITING_ACK, DELAY_RESYNC);
}
private void transitionsTo(State... validTransitionStates) {
// Also, everything may transition to UNINITIALISED
to = EnumSet.of(UNINITIALISED, validTransitionStates);
}
}
private final FuzzingBackOffGenerator backoffGenerator;
private final Log logger;
private final TimerService scheduler;
private final ReceiveOpChannel<M> channel;
private final SendOpService<M> submitService;
private final Listener<M> listener;
// State variables
private State state = State.UNINITIALISED;
private final TransformQueue<M> queue;
private String sessionId;
private int retryVersion = -1;
private DiscardableCallback submitCallback; // mutable to discard out of date ones
private DiscardableCallback versionCallback;
public GenericOperationChannel(TimerService scheduler, Transformer<M> transformer,
ReceiveOpChannel<M> channel, SendOpService<M> submitService,
Listener<M> listener, Log logger) {
this(new FuzzingBackOffGenerator(1500, 1800 * 1000, 0.5),
scheduler, transformer, channel, submitService, listener, logger);
}
public GenericOperationChannel(FuzzingBackOffGenerator generator, TimerService scheduler,
Transformer<M> transformer, ReceiveOpChannel<M> channel, SendOpService<M> submitService,
Listener<M> listener, Log logger) {
this.backoffGenerator = generator;
this.scheduler = scheduler;
this.queue = new TransformQueue<M>(transformer);
this.channel = channel;
this.submitService = submitService;
this.listener = listener;
this.logger = logger;
}
public boolean isConnected() {
// UNINITIALISED implies sessionId == null.
assert state != State.UNINITIALISED || sessionId == null;
return sessionId != null;
}
public int revision() {
checkConnected();
return queue.revision();
}
public void connect(int revision, String sessionId) {
Preconditions.checkState(!isConnected(), "Already connected");
Preconditions.checkNotNull(sessionId, "Null sessionId");
Preconditions.checkArgument(revision >= 0, "Invalid revision, %s", revision);
this.sessionId = sessionId;
channel.connect(revision, receiveListener);
queue.init(revision);
setState(State.ALL_ACKED);
}
public void disconnect() {
checkConnected();
channel.disconnect();
sessionId = null;
setState(State.UNINITIALISED);
}
/**
* @return true if there are no queued or unacknowledged ops
*/
public boolean isClean() {
checkConnected();
boolean ret = !queue.hasQueuedClientOps() && !queue.hasUnacknowledgedClientOps();
// isClean() implies ALL_ACKED
assert !ret || state == State.ALL_ACKED;
return ret;
}
public void send(M operation) {
checkConnected();
queue.clientOp(operation);
// Defer the send to allow multiple ops to batch up, and
// to avoid waiting for the browser's network stack in case
// we are in a time critical piece of code. Note, we could even
// go further and avoid doing the transform inside the queue.
if (!queue.hasUnacknowledgedClientOps()) {
assert state == State.ALL_ACKED;
scheduler.schedule(maybeSendTask);
}
}
public M peek() {
checkConnected();
return queue.hasServerOp() ? queue.peekServerOp() : null;
}
public M receive() {
checkConnected();
return queue.hasServerOp() ? queue.removeServerOp() : null;
}
/**
* Brings the state variable to the given value.
*
* <p>Verifies that other member variables are are in the correct state.
*/
private void setState(State newState) {
// Check transitioning from valid old state
State oldState = state;
assert oldState.to.contains(newState)
: "Invalid state transition " + oldState + " -> " + newState;
// Check consistency of variables with new state
checkState(newState);
state = newState;
}
private void checkState(State newState) {
switch (newState) {
case UNINITIALISED:
assert sessionId == null;
break;
case ALL_ACKED:
assert sessionId != null;
assert queue.revision() >= 0;
assert isDiscarded(submitCallback);
assert isDiscarded(versionCallback);
assert retryVersion == -1;
assert !queue.hasUnacknowledgedClientOps();
assert !scheduler.isScheduled(delayedResyncTask);
break;
case WAITING_ACK:
assert !isDiscarded(submitCallback);
assert isDiscarded(versionCallback);
assert retryVersion == -1;
assert !scheduler.isScheduled(maybeSendTask);
assert !scheduler.isScheduled(delayedResyncTask);
break;
case DELAY_RESYNC:
assert isDiscarded(submitCallback);
assert isDiscarded(versionCallback);
assert retryVersion == -1;
assert !scheduler.isScheduled(maybeSendTask);
assert scheduler.isScheduled(delayedResyncTask);
break;
case WAITING_SYNC:
assert isDiscarded(submitCallback);
assert !isDiscarded(versionCallback);
assert !scheduler.isScheduled(maybeSendTask);
assert !scheduler.isScheduled(delayedResyncTask);
break;
default:
throw new AssertionError("State " + state + " not implemented");
}
}
private void delayResync() {
scheduler.scheduleDelayed(delayedResyncTask, backoffGenerator.next().targetDelay);
setState(State.DELAY_RESYNC);
}
private void doResync() {
versionCallback = new DiscardableCallback() {
@Override public void success(int appliedRevision) {
logger.log(Level.INFO, "version callback returned @", appliedRevision);
retryVersion = appliedRevision;
maybeSynced();
}
};
submitService.requestRevision(versionCallback);
setState(State.WAITING_SYNC);
}
private void maybeSend() {
if (queue.hasUnacknowledgedClientOps()) {
logger.log(Level.INFO, state, ", Has ", queue.unackedClientOpsCount(), " unacked...");
return;
}
queue.pushQueuedOpsToUnacked();
sendUnackedOps();
}
/**
* Sends unacknowledged ops and transitions to the WAITING_ACK state
*/
private void sendUnackedOps() {
List<M> ops = queue.unackedClientOps();
assert ops.size() > 0;
logger.log(Level.INFO, "Sending ", ops.size(), " ops @", queue.revision());
submitCallback = new DiscardableCallback() {
@Override void success(int appliedRevision) {
maybeEagerlyHandleAck(appliedRevision);
}
};
submitService.submitOperations(queue.revision(), ops, submitCallback);
setState(State.WAITING_ACK);
}
private void onIncomingOperation(int revision, M operation) {
logger.log(Level.INFO, "Incoming ", revision, " ", state);
queue.serverOp(revision, operation);
listener.onRemoteOp(operation);
}
private void onAckOwnOperation(int resultingRevision, M ackedOp) {
boolean alreadyAckedByXhr = queue.expectedAck(resultingRevision);
if (alreadyAckedByXhr) {
// Nothing to do, just receiving expected operations that we've
// already handled by the optimization in maybeEagerlyHandleAck()
return;
}
boolean allAcked = queue.ackClientOp(resultingRevision);
logger.log(Level.INFO, "Ack @", resultingRevision, ", ",
queue.unackedClientOpsCount(), " ops remaining");
// If we have more ops to send and no unacknowledged ops,
// then schedule a send.
if (allAcked) {
allAcked();
}
listener.onAck(ackedOp, isClean());
}
private void maybeEagerlyHandleAck(int appliedRevision) {
List<M> ownOps = queue.ackOpsIfVersionMatches(appliedRevision);
if (ownOps == null) {
return;
}
logger.log(Level.INFO, "Eagerly acked @", appliedRevision);
// Special optimization: there were no concurrent ops on the server,
// so we don't need to wait for them or even our own ops on the channel.
// We just throw back our own ops to our listeners as if we had
// received them from the server (we expect they should exactly
// match the server history we will shortly receive on the channel).
assert !queue.hasUnacknowledgedClientOps();
allAcked();
boolean isClean = isClean();
for (int i = 0; i < ownOps.size(); i++) {
boolean isLast = i == ownOps.size() - 1;
listener.onAck(ownOps.get(i), isClean && isLast);
}
}
private void allAcked() {
// This also counts as an early sync
synced();
// No point waiting for the XHR to come back, we're already acked.
submitCallback.discard();
setState(State.ALL_ACKED);
if (queue.hasQueuedClientOps()) {
scheduler.schedule(maybeSendTask);
}
}
private void maybeSynced() {
if (state == State.WAITING_SYNC && retryVersion != -1 && queue.revision() >= retryVersion) {
// Our ping has returned.
synced();
if (queue.hasUnacknowledgedClientOps()) {
// We've synced and didn't see our unacked ops, so they never made it (we
// are not handling the case of ops that hang around on the network and
// make it after a very long time, i.e. after a sync round trip. This
// scenario most likely extremely rare).
// Send the unacked ops again.
sendUnackedOps();
}
}
}
/**
* We have reached a state where we are confident we know whether any unacked
* ops made it to the server.
*/
private void synced() {
logger.log(Level.INFO, "synced @", queue.revision());
retryVersion = -1;
scheduler.cancel(delayedResyncTask);
backoffGenerator.reset();
if (versionCallback != null) {
versionCallback.discard();
}
}
private void checkConnected() {
Preconditions.checkState(isConnected(), "Not connected");
}
private boolean isDiscarded(DiscardableCallback c) {
return c == null || c.discarded;
}
private void fail(Throwable e) {
logger.log(Level.WARNING, "channel.fail()");
if (!isConnected()) {
logger.log(Level.WARNING, "not connected");
return;
}
logger.log(Level.WARNING, "Permanent failure");
disconnect();
listener.onError(e);
}
@VisibleForTesting State getState() {
return state;
}
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.shared;
import com.google.common.base.Preconditions;
import com.google.walkaround.slob.shared.SlobModel.Slob;
/**
* A {@link Slob} and its current version. Mutable.
*
* @author ohler@google.com (Christian Ohler)
*/
public class StateAndVersion {
private final Slob state;
private long version;
public StateAndVersion(Slob state, long version) {
Preconditions.checkNotNull(state, "Null state");
this.state = state;
this.version = version;
}
public Slob getState() {
return state;
}
public long getVersion() {
return version;
}
public void apply(ChangeData<String> delta) throws ChangeRejected {
state.apply(delta);
version++;
}
@Override public String toString() {
return "StateAndVersion(" + state + ", " + version + ")";
}
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.shared;
/**
* Thrown when a snapshot cannot be deserialized into a model object for
* whatever reason.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class InvalidSnapshot extends Exception {
private static final long serialVersionUID = 925894689433745706L;
public InvalidSnapshot() {
super();
}
public InvalidSnapshot(String message, Throwable cause) {
super(message, cause);
}
public InvalidSnapshot(String message) {
super(message);
}
public InvalidSnapshot(Throwable cause) {
super(cause);
}
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.shared;
import java.util.List;
import javax.annotation.Nullable;
/**
* Represents a domain of shared live objects (slobs).
*
* @author danilatos@google.com (Daniel Danilatos)
*/
// TODO(danilatos): Have deserialize/serialize operation methods,
// and pass reified ops into the other methods like apply() & transform.
public interface SlobModel {
/**
* Read access to an object in this domain.
*/
interface ReadableSlob {
/**
* Returns a serialized form of the object. Can be null if the object has no
* history.
*/
@Nullable String snapshot();
/**
* Returns text to be indexed for search purposes.
*/
String getIndexedHtml();
}
/**
* Read/write access to an object in this domain.
*/
interface Slob extends ReadableSlob {
/**
* Applies a delta to the object.
*
* @throws ChangeRejected if the change is invalid. If
* {@link ChangeRejected} is thrown, the object MUST remain in the
* previous state, ready for application of a valid operation.
*/
void apply(ChangeData<String> payload) throws ChangeRejected;
}
/**
* Creates an object belonging to this domain.
*
* @param snapshot initial snapshot from which to deserialize. null if this is a
* completely new object.
*/
Slob create(@Nullable String snapshot) throws InvalidSnapshot;
/**
* Transforms operations on objects in this domain.
*
* @return the transformed client payloads (they will need to be re-wrapped).
*
* @throws ChangeRejected if the client ops were invalid or not compatible
* with eachother. The server ops are guaranteed to have passed
* through the apply() method successfully and therefore are known
* to be valid.
*/
List<String> transform(List<ChangeData<String>> clientOps, List<ChangeData<String>> serverOps)
throws ChangeRejected;
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.shared;
/**
* Thrown when a model change was rejected.
*
* When this exception is thrown, the model must remain in the state prior to
* the rejected change, ready for application of a different, valid change.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class ChangeRejected extends Exception {
private static final long serialVersionUID = 866300980861599406L;
public ChangeRejected() {
super();
}
public ChangeRejected(String message, Throwable cause) {
super(message, cause);
}
public ChangeRejected(String message) {
super(message);
}
public ChangeRejected(Throwable cause) {
super(cause);
}
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.shared;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
/**
* Represents a change in the mutation history of an object.
*
* @param <T> payload type. Parametrised so the server can use String and the
* client can treat it as a reified JSON object. Ideally both client
* and server would use the same type.
*
* TODO(danilatos): Two things need to happen first. 1) A JsoView-like
* interface needs to be created, with single-jso-impl client
* implementation, and org.json-backed server implementation. 2) PST
* needs to be fixed to generate less stupid proto implementations, in
* fact, just one simple implementation backed by a shared json
* interface such as mentioned in 1. Then "T" would always be that
* interface (the server could abolish its use of String, because the
* json interface would be directly adaptable to a protobuf).
*
* @author danilatos@google.com (Daniel Danilatos)
*/
// TODO(danilatos): Rename to Delta
public final class ChangeData<T> {
private final ClientId clientId;
private final T payload;
public ChangeData(ClientId clientId, T payload) {
Preconditions.checkNotNull(clientId, "Null clientId");
Preconditions.checkNotNull(payload, "Null payload");
this.clientId = clientId;
this.payload = payload;
}
public ClientId getClientId() {
return clientId;
}
public T getPayload() {
return payload;
}
@Override public String toString() {
return "ChangeData(" + clientId + ", " + payload + ")";
}
@Override public final boolean equals(Object o) {
if (o == this) { return true; }
if (!(o instanceof ChangeData)) { return false; }
ChangeData<?> other = (ChangeData<?>) o;
return Objects.equal(clientId, other.clientId)
&& Objects.equal(payload, other.payload);
}
@Override public final int hashCode() {
return Objects.hashCode(clientId, payload);
}
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.shared;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import java.io.Serializable;
/**
* A client ID. See walkaround.proto for more information.
*
* @author ohler@google.com (Christian Ohler)
*/
public final class ClientId implements Serializable {
private static final long serialVersionUID = 897917221735180820L;
private final String id;
public ClientId(String id) {
Preconditions.checkNotNull(id, "Null id");
this.id = id;
}
public String getId() {
return id;
}
@Override public String toString() {
return "ClientId(" + id + ")";
}
@Override public final boolean equals(Object o) {
if (o == this) { return true; }
if (!(o instanceof ClientId)) { return false; }
ClientId other = (ClientId) o;
return Objects.equal(id, other.id);
}
@Override public final int hashCode() {
return Objects.hashCode(id);
}
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.shared;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Objects;
import java.io.Serializable;
/**
* Type-safe wrapper around a raw object id.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public final class SlobId implements Serializable {
private static final long serialVersionUID = 178314993219268135L;
private final String id;
public SlobId(String id) {
this.id = checkNotNull(id, "Null id");
}
public String getId() {
return id;
}
@Override public String toString() {
return "SlobId(" + id + ")";
}
@Override public final boolean equals(Object o) {
if (o == this) { return true; }
if (!(o instanceof SlobId)) { return false; }
SlobId other = (SlobId) o;
return Objects.equal(id, other.id);
}
@Override public final int hashCode() {
return Objects.hashCode(id);
}
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.shared;
/**
* Exception thrown by application code to indicate that there was a problem
* parsing or interpreting a message, so that low-level code can handle the
* situation as an error condition.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
@SuppressWarnings("serial")
public class MessageException extends Exception {
public MessageException(String message, Throwable cause) {
super(message, cause);
}
public MessageException(String message) {
super(message);
}
public MessageException(Throwable cause) {
super(cause);
}
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
import com.google.appengine.api.memcache.Expiration;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
import com.google.common.collect.ImmutableList;
import com.google.inject.Inject;
import com.google.walkaround.proto.ServerMutateRequest;
import com.google.walkaround.proto.ServerMutateResponse;
import com.google.walkaround.slob.server.MutationLog.DeltaIterator;
import com.google.walkaround.slob.server.MutationLog.MutationLogFactory;
import com.google.walkaround.slob.server.SlobMessageRouter.TooManyListenersException;
import com.google.walkaround.slob.shared.ChangeData;
import com.google.walkaround.slob.shared.ChangeRejected;
import com.google.walkaround.slob.shared.ClientId;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.slob.shared.SlobModel.ReadableSlob;
import com.google.walkaround.slob.shared.StateAndVersion;
import com.google.walkaround.util.server.RetryHelper.PermanentFailure;
import com.google.walkaround.util.server.RetryHelper.RetryableFailure;
import com.google.walkaround.util.server.appengine.CheckedDatastore;
import com.google.walkaround.util.server.appengine.CheckedDatastore.CheckedTransaction;
import com.google.walkaround.util.server.appengine.MemcacheTable;
import com.google.walkaround.util.server.appengine.MemcacheTable.IdentifiableValue;
import com.google.walkaround.util.shared.RandomBase64Generator;
import org.waveprotocol.wave.model.util.Pair;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Datastore (and other app enginy things) backed implementation.
*
* @author danilatos@google.com (Daniel Danilatos)
* @author ohler@google.com (Christian Ohler)
*/
public class SlobStoreImpl implements SlobStore {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(SlobStoreImpl.class.getName());
// Split out because InternalPostCommitAction can't depend on the full
// SlobStoreImpl, which needs an AccessChecker and thus a UserContext, which
// task queue tasks don't have.
static class Cache {
private final MemcacheTable<SlobId, Long> currentVersions;
@Inject Cache(MemcacheTable.Factory memcacheFactory,
@SlobRootEntityKind String rootEntityKind) {
this.currentVersions = memcacheFactory.create(MEMCACHE_TAG_PREFIX + rootEntityKind);
}
}
static class InternalPostCommitAction implements PostCommitAction {
@Inject Cache cache;
@Override public void unreliableImmediatePostCommit(SlobId slobId, long resultingVersion,
ReadableSlob resultingState) {
// We have to put null rather than deleting since what we do here must
// interfere with a concurrent getIdentifiable/putIfUntouched sequence,
// and MemcacheService's Javadoc does not specify that putIfUntouched will
// abort if the value was absent during the lookup and delete has been
// called between the lookup and putIfUntouched.
cache.currentVersions.put(slobId, null);
}
@Override public void reliableDelayedPostCommit(SlobId slobId) {
cache.currentVersions.put(slobId, null);
}
}
private static final String MEMCACHE_TAG_PREFIX = "slobversion-";
private static final int VERSION_NUMBER_CACHE_EXPIRATION_MILLIS = 24 * 60 * 60 * 1000;
private final CheckedDatastore datastore;
private final MutationLogFactory mutationLogFactory;
private final SlobMessageRouter messageRouter;
private final AffinityMutationProcessor defaultProcessor;
private final AccessChecker accessChecker;
private final PostMutateHook postMutateHook;
private final String rootEntityKind;
private final Cache cache;
private final LocalMutationProcessor localProcessor;
@Inject
public SlobStoreImpl(CheckedDatastore datastore,
MutationLogFactory mutationLogFactory,
SlobMessageRouter messageRouter,
Random random, RandomBase64Generator random64,
AffinityMutationProcessor defaultProcessor,
LocalMutationProcessor localProcessor,
AccessChecker accessChecker,
PostMutateHook postMutateHook,
@SlobRootEntityKind String rootEntityKind,
Cache cache) {
this.datastore = datastore;
this.mutationLogFactory = mutationLogFactory;
this.messageRouter = messageRouter;
this.defaultProcessor = defaultProcessor;
this.localProcessor = localProcessor;
this.accessChecker = accessChecker;
this.postMutateHook = postMutateHook;
this.rootEntityKind = rootEntityKind;
this.cache = cache;
}
@Override
public Pair<ConnectResult, String> connect(SlobId slobId, ClientId clientId)
throws SlobNotFoundException, IOException, AccessDeniedException {
return connectOrReconnect(slobId, clientId, true);
}
@Override
public ConnectResult reconnect(SlobId slobId, ClientId clientId)
throws SlobNotFoundException, IOException, AccessDeniedException {
return connectOrReconnect(slobId, clientId, false).getFirst();
}
private Pair<ConnectResult, String> connectOrReconnect(
SlobId slobId, ClientId clientId, boolean withSnapshot)
throws SlobNotFoundException, IOException, AccessDeniedException {
accessChecker.checkCanRead(slobId);
String snapshot;
long version;
IdentifiableValue<Long> cachedVersion = cache.currentVersions.getIdentifiable(slobId);
if (!withSnapshot && cachedVersion != null && cachedVersion.getValue() != null) {
version = cachedVersion.getValue();
log.info("Version number from cache: " + version);
snapshot = null;
} else {
try {
CheckedTransaction tx = datastore.beginTransaction();
try {
MutationLog mutationLog = mutationLogFactory.create(tx, slobId);
if (withSnapshot) {
StateAndVersion x = mutationLog.reconstruct(null);
version = x.getVersion();
snapshot = x.getState().snapshot();
} else {
version = mutationLog.getVersion();
snapshot = null;
}
if (version == 0) {
throw new SlobNotFoundException(
"Slob " + slobId + " (" + rootEntityKind + ") not found");
}
} finally {
tx.rollback();
}
} catch (PermanentFailure e) {
throw new IOException(e);
} catch (RetryableFailure e) {
throw new IOException(e);
}
cache.currentVersions.putIfUntouched(slobId, cachedVersion, version,
// Since the cache is invalidated by a task queue task, we only need this expiration to
// protect from admins deleting tasks and similar situations.
Expiration.byDeltaMillis(VERSION_NUMBER_CACHE_EXPIRATION_MILLIS));
}
String channelToken;
if (clientId != null) {
try {
channelToken = messageRouter.connectListener(slobId, clientId);
} catch (TooManyListenersException e) {
channelToken = null;
}
} else {
channelToken = null;
}
return Pair.of(new ConnectResult(channelToken, version), snapshot);
}
@Override
public String loadAtVersion(SlobId slobId, @Nullable Long version)
throws IOException, AccessDeniedException {
accessChecker.checkCanRead(slobId);
try {
CheckedTransaction tx = datastore.beginTransaction();
try {
MutationLog l = mutationLogFactory.create(tx, slobId);
return l.reconstruct(version).getState().snapshot();
} finally {
tx.rollback();
}
} catch (PermanentFailure e) {
throw new IOException(e);
} catch (RetryableFailure e) {
throw new IOException(e);
}
}
@Override
public HistoryResult loadHistory(SlobId slobId, long startVersion, @Nullable Long endVersion)
throws SlobNotFoundException, IOException, AccessDeniedException {
accessChecker.checkCanRead(slobId);
IdentifiableValue<Long> cachedVersion = cache.currentVersions.getIdentifiable(slobId);
log.info("loadHistory(" + slobId + ", " + startVersion + " - " + endVersion + "); cached: "
+ cachedVersion);
if (cachedVersion != null && cachedVersion.getValue() != null
&& startVersion >= cachedVersion.getValue()
&& endVersion == null) {
return new HistoryResult(ImmutableList.<ChangeData<String>>of(), false);
}
final int MAX_MILLIS = 3 * 1000;
try {
CheckedTransaction tx = datastore.beginTransaction();
try {
// TODO(ohler): put current version into cache
DeltaIterator result = mutationLogFactory.create(tx, slobId).forwardHistory(
startVersion, endVersion);
if (!result.hasNext()) {
return new HistoryResult(ImmutableList.<ChangeData<String>>of(), false);
}
ImmutableList.Builder<ChangeData<String>> list = ImmutableList.builder();
Stopwatch stopwatch = new Stopwatch().start();
do {
list.add(result.next());
} while (result.hasNext() && stopwatch.elapsedMillis() < MAX_MILLIS);
return new HistoryResult(list.build(), result.hasNext());
} finally {
tx.rollback();
}
} catch (PermanentFailure e) {
throw new IOException(e);
} catch (RetryableFailure e) {
// TODO(danilatos): Retry?
throw new IOException(e);
}
}
@Override
public MutateResult mutateObject(ServerMutateRequest req)
// TODO(ohler): Actually throw SlobNotFoundException.
throws SlobNotFoundException, IOException, AccessDeniedException {
SlobId objectId = new SlobId(req.getSession().getObjectId());
accessChecker.checkCanModify(objectId);
Preconditions.checkArgument(req.getVersion() != 0,
// NOTE(ohler): In Google Wave, there were security concerns around
// creating objects by submitting deltas against version 0. I'm not
// sure Walkaround has the same problems, but let's disallow it anyway.
"Can't create objects with mutateObject()");
ServerMutateResponse response = defaultProcessor.mutateObject(req);
MutateResult result = new MutateResult(response.getResultingVersion(), response.getIndexData());
// Sending the broadcast message is not critical, so run the
// postMutateHook first.
postMutateHook.run(objectId, result);
if (response.getBroadcastData() != null) {
messageRouter.publishMessages(objectId, response.getBroadcastData());
}
return result;
}
@Override
public void newObject(CheckedTransaction tx,
SlobId slobId, String metadata, List<ChangeData<String>> initialHistory,
boolean inhibitPreAndPostCommit)
throws SlobAlreadyExistsException, AccessDeniedException, RetryableFailure, PermanentFailure {
Preconditions.checkNotNull(tx, "Null tx");
Preconditions.checkNotNull(slobId, "Null slobId");
Preconditions.checkNotNull(metadata, "Null metadata");
Preconditions.checkNotNull(initialHistory, "Null initialHistory");
accessChecker.checkCanCreate(slobId);
MutationLog l = mutationLogFactory.create(tx, slobId);
String existingMetadata = l.getMetadata();
if (existingMetadata != null) {
log.info("Slob " + slobId + " already exists: found metadata: " + existingMetadata);
throw new SlobAlreadyExistsException(slobId + " already exists");
}
// Check for the existence of deltas as well because legacy conv
// wavelets have no metadata entity.
long version = l.getVersion();
if (version != 0) {
log.info("Slob " + slobId + " already exists at version " + version);
throw new SlobAlreadyExistsException(slobId + " already exists (found deltas)");
}
MutationLog.Appender appender = l.prepareAppender().getAppender();
try {
appender.appendAll(initialHistory);
} catch (ChangeRejected e) {
throw new IllegalArgumentException("Invalid initial history: " + initialHistory, e);
}
l.putMetadata(metadata);
appender.finish();
if (!inhibitPreAndPostCommit) {
localProcessor.runPreCommit(tx, slobId, appender);
localProcessor.schedulePostCommit(tx, slobId, appender);
}
}
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.slob.shared.SlobModel.ReadableSlob;
import com.google.walkaround.util.server.RetryHelper.PermanentFailure;
import com.google.walkaround.util.server.RetryHelper.RetryableFailure;
import com.google.walkaround.util.server.appengine.CheckedDatastore.CheckedTransaction;
/**
* Called in {@link SlobStore#mutateObject} before committing a sequence of
* changes to an object.
*
* @author ohler@google.com (Christian Ohler)
*/
public interface PreCommitAction {
void run(CheckedTransaction tx, SlobId objectId,
long resultingVersion, ReadableSlob resultingState)
throws RetryableFailure, PermanentFailure;
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.walkaround.proto.ServerMutateRequest;
import com.google.walkaround.slob.shared.ChangeData;
import com.google.walkaround.slob.shared.ClientId;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.util.server.RetryHelper.PermanentFailure;
import com.google.walkaround.util.server.RetryHelper.RetryableFailure;
import com.google.walkaround.util.server.appengine.CheckedDatastore.CheckedTransaction;
import org.waveprotocol.wave.model.util.Pair;
import java.io.IOException;
import java.util.List;
import javax.annotation.Nullable;
/**
* Interactions with the shared live object (slob) store.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public interface SlobStore {
/**
* Provides a connection for dealing with an object, along with a snapshot of
* the object state.
*/
Pair<ConnectResult, String> connect(SlobId slobId, ClientId clientId)
throws SlobNotFoundException, IOException, AccessDeniedException;
/**
* Connects without returning a snapshot.
*/
ConnectResult reconnect(SlobId slobId, ClientId clientId)
throws SlobNotFoundException, IOException, AccessDeniedException;
// Returns a snapshot. TODO(ohler): make snapshot type a generic parameter or something
String loadAtVersion(SlobId slobId, @Nullable Long version)
throws SlobNotFoundException, IOException, AccessDeniedException;
/**
* Loads the history of an object. If the history is large, not all requested
* data may be returned, but the result object will contain this information;
* the caller should then ask again for the next chunk. The returned data will
* always begin at startVersion and be contiguous.
*
* @param startVersion The version of the object before the first change to
* return.
* @param endVersion The version of the object after the last change to
* return, or null for current version.
* @return the historical mutations, as many as could be retrieved in one go.
* @throws SlobNotFoundException if the object is not found
*/
HistoryResult loadHistory(SlobId slobId, long startVersion, @Nullable Long endVersion)
throws SlobNotFoundException, IOException, AccessDeniedException;
/**
* Processes the given mutate request.
*/
MutateResult mutateObject(ServerMutateRequest req)
throws SlobNotFoundException, IOException, AccessDeniedException;
/**
* Creates a new object.
*/
void newObject(CheckedTransaction tx, SlobId slobId, String metadata,
List<ChangeData<String>> initialHistory, boolean inhibitPreAndPostCommit)
throws SlobAlreadyExistsException, AccessDeniedException,
RetryableFailure, PermanentFailure;
/** Result of a history fetch. */
final class HistoryResult {
private final ImmutableList<ChangeData<String>> data;
private final boolean hasMore;
public HistoryResult(ImmutableList<ChangeData<String>> data,
boolean hasMore) {
Preconditions.checkNotNull(data, "Null data");
this.data = data;
this.hasMore = hasMore;
}
public ImmutableList<ChangeData<String>> getData() {
return data;
}
public boolean hasMore() {
return hasMore;
}
@Override public String toString() {
return "HistoryResult(" + data + ", " + hasMore + ")";
}
}
/**
* Information used to establish a live connection to the specified object.
*/
final class ConnectResult {
// Null means no live connection is possible.
@Nullable private final String channelToken;
private final long version;
public ConnectResult(@Nullable String channelToken, long version) {
this.channelToken = channelToken;
this.version = version;
}
@Nullable public String getChannelToken() {
return channelToken;
}
public long getVersion() {
return version;
}
@Override public String toString() {
return "ConnectResult(" + channelToken + ", " + version + ")";
}
}
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
import com.google.appengine.api.datastore.Key;
import com.google.inject.Inject;
import com.google.inject.Module;
import com.google.inject.PrivateBinder;
import com.google.inject.PrivateModule;
import com.google.inject.Provider;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import com.google.inject.multibindings.Multibinder;
import com.google.walkaround.slob.server.MutationLog.MutationLogFactory;
import com.google.walkaround.slob.shared.SlobId;
import java.lang.annotation.Annotation;
import java.util.logging.Logger;
/**
* Helper for Guice {@link PrivateModule}s that configure instances of the
* slob store.
*
* @author ohler@google.com (Christian Ohler)
*/
public class StoreModuleHelper {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(StoreModuleHelper.class.getName());
public static <F, P> Module factoryModule(Class<F> factoryClass, Class<P> productClass) {
return new FactoryModuleBuilder()
.implement(productClass, productClass)
.build(factoryClass);
}
private static class FacilitiesImpl implements SlobFacilities {
// These are providers since many users will only need one.
@Inject Provider<SlobStore> slobStore;
@Inject Provider<LocalMutationProcessor> localMutationProcessor;
@Inject Provider<MutationLogFactory> mutationLogFactory;
@Inject @SlobRootEntityKind String rootEntityKind;
@Inject Provider<PostCommitActionScheduler> postCommitActionScheduler;
@Override public String toString() {
return "SlobFacilities(" + rootEntityKind + ")";
}
@Override public SlobStore getSlobStore() {
return slobStore.get();
}
@Override public LocalMutationProcessor getLocalMutationProcessor() {
return localMutationProcessor.get();
}
@Override public MutationLogFactory getMutationLogFactory() {
return mutationLogFactory.get();
}
@Override public String getRootEntityKind() {
return rootEntityKind;
}
@Override public Key makeRootEntityKey(SlobId slobId) {
return MutationLog.makeRootEntityKey(rootEntityKind, slobId);
}
@Override public SlobId parseRootEntityKey(Key key) {
return MutationLog.parseRootEntityKey(rootEntityKind, key);
}
@Override public PostCommitActionScheduler getPostCommitActionScheduler() {
return postCommitActionScheduler.get();
}
}
public static void makeBasicBindingsAndExposures(PrivateBinder binder,
Class<? extends Annotation> annotation) {
binder.bind(SlobFacilities.class).to(FacilitiesImpl.class);
binder.bind(SlobStore.class).to(SlobStoreImpl.class);
binder.install(factoryModule(MutationLogFactory.class, MutationLog.class));
binder.bind(MutationLogFactory.class).annotatedWith(annotation).to(MutationLogFactory.class);
binder.bind(SlobStore.class).annotatedWith(annotation).to(SlobStore.class);
binder.bind(LocalMutationProcessor.class).annotatedWith(annotation)
.to(LocalMutationProcessor.class);
binder.bind(SlobFacilities.class).annotatedWith(annotation).to(FacilitiesImpl.class);
binder.expose(MutationLogFactory.class).annotatedWith(annotation);
binder.expose(SlobStore.class).annotatedWith(annotation);
binder.expose(LocalMutationProcessor.class).annotatedWith(annotation);
binder.expose(SlobFacilities.class).annotatedWith(annotation);
// Make sure a binding for the Set exists.
Multibinder.newSetBinder(binder, PreCommitAction.class);
// Make sure a binding for the Set exists.
Multibinder.newSetBinder(binder, PostCommitAction.class);
}
public static void bindEntityKinds(PrivateBinder binder, String prefix) {
binder.bind(String.class).annotatedWith(SlobRootEntityKind.class).toInstance(prefix);
binder.bind(String.class).annotatedWith(SlobDeltaEntityKind.class)
.toInstance(prefix + "Delta");
binder.bind(String.class).annotatedWith(SlobSnapshotEntityKind.class)
.toInstance(prefix + "Snapshot");
binder.bind(String.class).annotatedWith(SlobSynchronizationEntityKind.class)
.toInstance(prefix + "Sync");
}
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
import com.google.appengine.api.backends.BackendService;
import com.google.inject.Inject;
import com.google.walkaround.util.server.auth.DigestUtils2.Secret;
import com.google.walkaround.util.server.servlet.PermissionDeniedException;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
/**
* Security checks for slob store requests.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
// If we add any other backend servlets, we should make this a servlet filter.
public class StoreAccessChecker {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(StoreAccessChecker.class.getName());
public static final String WALKAROUND_TRUSTED_HEADER = "X-Walkaround-Trusted";
private final BackendService backends;
private final Secret secret;
@Inject
public StoreAccessChecker(BackendService backends, Secret secret) {
this.backends = backends;
this.secret = secret;
}
public void checkPermittedStoreRequest(HttpServletRequest req) {
// Either Check A or B are sufficient, but we do both for defense in depth.
boolean checkA, checkB;
String headerSecret = req.getHeader(WALKAROUND_TRUSTED_HEADER);
if (headerSecret == null) {
log.warning("No store access: Missing header secret");
checkA = false;
} else if (!secret.getHexData().equals(headerSecret)) {
log.warning("No store access: Wrong header secret " + obscured(headerSecret));
checkA = false;
} else {
checkA = true;
}
boolean runningOnBackend = (backends.getCurrentBackend() != null);
if (!runningOnBackend) {
log.warning("Access check failure - Not running on backend! "
+ "(running additional checks before dying...)");
checkB = false;
} else {
checkB = true;
}
if (checkA != checkB) {
log.severe("Access checks mismatched: a=" + checkA + ", b=" + checkB);
}
if (checkA && checkB) {
log.info("Store access permitted");
return;
} else {
throw new PermissionDeniedException("No store access");
}
}
/**
* Obscures secret strings (short strings aren't obscured, but they aren't
* very secure to begin with).
*/
private String obscured(String str) {
if (str.length() < 4) {
return str;
}
return str.substring(0, 4) + "...";
}
}
| 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.walkaround.slob.server;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Guice annotation for the number of milliseconds after which to expire the
* in-memory cache of a slob's current states.
*
* @author ohler@google.com (Christian Ohler)
*/
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface SlobLocalCacheExpirationMillis {}
| 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.walkaround.slob.server;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.memcache.Expiration;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.inject.Inject;
import com.google.walkaround.slob.server.handler.PostCommitTaskHandler;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.slob.shared.SlobModel.ReadableSlob;
import com.google.walkaround.util.server.RetryHelper;
import com.google.walkaround.util.server.RetryHelper.PermanentFailure;
import com.google.walkaround.util.server.RetryHelper.RetryableFailure;
import com.google.walkaround.util.server.appengine.CheckedDatastore;
import com.google.walkaround.util.server.appengine.CheckedDatastore.CheckedTransaction;
import com.google.walkaround.util.server.appengine.MemcacheTable;
import java.util.Date;
import java.util.Random;
import java.util.Set;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Schedules task queue tasks that invoke {@link PostCommitAction} in a
* throttled manner.
*
* @author ohler@google.com (Christian Ohler)
*/
public class PostCommitActionScheduler {
// Protocol (all of the following is for a given slob; different slobs are
// independent (except that they compete for CPU and other resources)):
//
// We keep an "action pending" marker in memcache. The presence of this
// marker means that a task queue task is scheduled that will execute some
// time in the future and run the post-commit actions.
//
// On every slob update in the datastore:
//
// - begin transaction
// - slob update (some gets and puts on the entity group)
// - if marker not present, schedule task at time T
// - commit
// - if task scheduled, put marker into memcache, expiring at time T-buffer
// (buffer to compensate for clock skew)
//
// Task queue task:
//
// - do a datastore put on the entity group. This ensures that this task runs
// outside of any "if marker not present, schedule task, commit" block -- we
// either want that block to re-run, or this task to run after that block
// - run post-commit actions
//
// This protocol ensures that a task queue task will run after every update,
// since:
//
// - Start of task and update transaction never happen concurrently; may
// attempt in parallel but one will retry if so.
//
// - Tasks don't interfere with one another, and neither do updates (memcache
// entry may be overwritten with an earlier expiry but that's still
// correct).
//
// - Presence of the marker in memcache always implies that a task will run in
// the future, since we only put after successfully scheduling a task, and
// the expiry is before the ETA.
//
// - A task cannot begin during an update; so the update will either schedule
// a task, or a marker was present while the update was running. In both
// cases, a task will run after the update, which is the property we're
// after.
//
// (Still not convinced; need to use formal techniques.)
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(PostCommitActionScheduler.class.getName());
private final String MEMCACHE_TAG_PREFIX = "PostCommitActionPending-";
// Used in the key of sync entities.
private static final String SYNC_ENTITY_NAME = "sync";
private final Set<PostCommitAction> actions;
private final Queue postCommitActionQueue;
private final int postCommitActionIntervalMillis;
private final MemcacheTable<SlobId, Boolean> postCommitActionPending;
private final String rootEntityKind;
private final String syncEntityKind;
private final String taskUrl;
private final Random random;
// We treat the cache-clearing InternalPostCommitAction specially since we
// want it to always run first; otherwise, it could be preempted by
// user-defined PostCommitActions that always crash.
private final SlobStoreImpl.InternalPostCommitAction internalPostCommit;
private final CheckedDatastore datastore;
@Inject
public PostCommitActionScheduler(Set<PostCommitAction> actions,
@PostCommitActionQueue Queue postCommitActionQueue,
@PostCommitActionIntervalMillis int postCommitActionIntervalMillis,
MemcacheTable.Factory memcacheFactory,
@SlobRootEntityKind String rootEntityKind,
@SlobSynchronizationEntityKind String syncEntityKind,
@PostCommitTaskUrl String taskUrl,
Random random,
SlobStoreImpl.InternalPostCommitAction internalPostCommit,
CheckedDatastore datastore) {
this.actions = actions;
this.postCommitActionQueue = postCommitActionQueue;
this.postCommitActionIntervalMillis = postCommitActionIntervalMillis;
this.postCommitActionPending = memcacheFactory.create(MEMCACHE_TAG_PREFIX + rootEntityKind);
this.rootEntityKind = rootEntityKind;
this.syncEntityKind = syncEntityKind;
this.taskUrl = taskUrl;
this.random = random;
this.internalPostCommit = internalPostCommit;
this.datastore = datastore;
}
private void scheduleTask(CheckedTransaction tx, final SlobId slobId, long taskEtaMillis)
throws PermanentFailure, RetryableFailure {
tx.enqueueTask(postCommitActionQueue,
TaskOptions.Builder.withUrl(taskUrl)
.param(PostCommitTaskHandler.STORE_TYPE_PARAM, rootEntityKind)
.param(PostCommitTaskHandler.SLOB_ID_PARAM, slobId.getId())
.etaMillis(taskEtaMillis));
}
/** Prefer {@link #prepareCommit} if you can. */
public void unconditionallyScheduleTask(CheckedTransaction tx, final SlobId slobId)
throws PermanentFailure, RetryableFailure {
// Can't short-circuit if actions.isEmpty() because we always have internalPostCommit.
long timeNowMillis = System.currentTimeMillis();
log.info("Scheduling post-commit actions on " + slobId
+ " (" + rootEntityKind + "); time now=" + timeNowMillis);
scheduleTask(tx, slobId, timeNowMillis);
}
public void prepareCommit(CheckedTransaction tx, final SlobId slobId,
final long resultingVersion, final ReadableSlob resultingState)
throws PermanentFailure, RetryableFailure {
// Can't short-circuit if actions.isEmpty() because we always have internalPostCommit.
@Nullable Long cacheEntryExpirationMillis;
if (postCommitActionPending.get(slobId) == Boolean.TRUE) {
log.info("Post-commit actions pending on " + slobId
+ " (" + rootEntityKind + "), not scheduling task");
cacheEntryExpirationMillis = null;
} else {
long delayMillis = postCommitActionIntervalMillis == 0 ? 0
: random.nextInt(postCommitActionIntervalMillis) + (postCommitActionIntervalMillis / 2L);
long timeNowMillis = System.currentTimeMillis();
cacheEntryExpirationMillis = timeNowMillis + delayMillis;
long taskEtaMillis = cacheEntryExpirationMillis
// We need to be sure that the cache entry expires before the task queue
// task runs, so we add some safety buffer in case the machine clocks
// are out of sync.
+ 2000;
log.info("Scheduling post-commit actions on " + slobId
+ " (" + rootEntityKind + "); time now=" + timeNowMillis
+ ", cache entry expiration=" + cacheEntryExpirationMillis
+ ", task eta=" + taskEtaMillis);
scheduleTask(tx, slobId, taskEtaMillis);
}
@Nullable final Long cacheEntryExpirationMillisFinal = cacheEntryExpirationMillis;
tx.runAfterCommit(new Runnable() {
@Override public void run() {
if (cacheEntryExpirationMillisFinal != null) {
postCommitActionPending.put(slobId, true,
Expiration.onDate(new Date(cacheEntryExpirationMillisFinal)));
}
for (PostCommitAction action : getActions()) {
log.info("Running immediate post-commit action " + action
+ " on " + slobId + " (" + rootEntityKind + ")");
action.unreliableImmediatePostCommit(slobId, resultingVersion, resultingState);
}
}
});
}
private Iterable<PostCommitAction> getActions() {
return Iterables.concat(ImmutableList.of(internalPostCommit), actions);
}
public void taskInvoked(final SlobId slobId) {
try {
new RetryHelper().run(new RetryHelper.VoidBody() {
@Override
public void run() throws RetryableFailure, PermanentFailure {
CheckedTransaction tx = datastore.beginTransaction();
tx.put(new Entity(KeyFactory.createKey(
MutationLog.makeRootEntityKey(rootEntityKind, slobId),
syncEntityKind, SYNC_ENTITY_NAME)));
tx.commit();
}
});
} catch (PermanentFailure e) {
throw new RuntimeException("Failed to touch sync entity, trying again later", e);
}
for (PostCommitAction action : getActions()) {
log.info("Running reliable post-commit action " + action
+ " on " + slobId + " (" + rootEntityKind + ")");
action.reliableDelayedPostCommit(slobId);
}
}
}
| 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.walkaround.slob.server;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Guice annotation for an App Engine task Queue for post-commit actions.
*
* @author ohler@google.com (Christian Ohler)
*/
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface PostCommitActionQueue {}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Guice annotation for the String that will be used as the object delta entity kind.
*
* @author ohler@google.com (Christian Ohler)
*/
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface SlobDeltaEntityKind {}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker;
import com.google.common.primitives.Ints;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.walkaround.proto.ServerMutateRequest;
import com.google.walkaround.proto.ServerMutateResponse;
import com.google.walkaround.proto.gson.ServerMutateResponseGsonImpl;
import com.google.walkaround.slob.server.MutationLog.DeltaIteratorProvider;
import com.google.walkaround.slob.server.MutationLog.MutationLogFactory;
import com.google.walkaround.slob.shared.ChangeData;
import com.google.walkaround.slob.shared.ChangeRejected;
import com.google.walkaround.slob.shared.ClientId;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.slob.shared.SlobModel;
import com.google.walkaround.util.server.MonitoringVars;
import com.google.walkaround.util.server.RetryHelper;
import com.google.walkaround.util.server.RetryHelper.PermanentFailure;
import com.google.walkaround.util.server.RetryHelper.RetryableFailure;
import com.google.walkaround.util.server.appengine.CheckedDatastore;
import com.google.walkaround.util.server.appengine.CheckedDatastore.CheckedTransaction;
import com.google.walkaround.util.server.servlet.BadRequestException;
import com.google.walkaround.util.server.writebatch.BatchingUpdateProcessor;
import com.google.walkaround.util.server.writebatch.TransactionFactory;
import com.google.walkaround.util.server.writebatch.UpdateResult;
import com.google.walkaround.util.server.writebatch.UpdateTransaction;
import com.google.walkaround.util.shared.ConcatenatingList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Accepts mutations on objects.
*
* Handles concurrent updates using transform, and write batching.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
// Singleton so that mutations that come in in different threads reach the same
// instance which can then process them in one batch.
@Singleton
public class LocalMutationProcessor {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(LocalMutationProcessor.class.getName());
// TODO(danilatos): Make these flags.
/** The maximum number of ops the server is willing to transform updates against */
private static final long MAX_TAIL_SIZE = 500;
/** A soft limit on the number of ops the server is willing save in a single batch */
private static final long MAX_BATCH_SIZE = 99;
// TODO(danilatos): Give these inner classes a bit of a manicure, after
// figuring out exactly what it is that bugs me about them.
private static class Processor extends BatchingUpdateProcessor<Update, UpResult, Tx> {
public Processor(TransactionFactory<UpResult, Tx> txFactory, RetryHelper retryHelper) {
super(txFactory, retryHelper);
}
}
private class Update {
private final SlobId objectId;
private final ClientId clientId;
private final long version;
// Payloads kept in addition to changes for the common non-transform case,
// and to avoid redundant info in toString().
private final ImmutableList<String> payloads;
public Update(SlobId id, ClientId clientId, long version, List<String> payloads) {
Preconditions.checkArgument(version >= 0, "Bad version %s", version);
this.objectId = Preconditions.checkNotNull(id, "Null id");
this.clientId = Preconditions.checkNotNull(clientId, "Null clientId");
this.payloads = ImmutableList.copyOf(Preconditions.checkNotNull(payloads, "Null payloads"));
this.version = version;
}
ImmutableList<ChangeData<String>> changes(List<String> payloads) {
ImmutableList.Builder<ChangeData<String>> b = ImmutableList.builder();
for (String payload : payloads) {
b.add(new ChangeData<String>(clientId, payload));
}
return b.build();
}
@Override
public String toString() {
return toString(true);
}
String toString(boolean full) {
return "Update(" + objectId + "," + clientId + "@" + version + "; "
+ (full
? payloads.toString()
: (payloads.size() + " ops, " + System.identityHashCode(this)))
+ ")";
}
}
/**
* TODO(danilatos): There is some confusion between this class and
* MutateResult, they are very similar. Fix this.
*/
private static class UpResult implements UpdateResult {
final long resultingRevision;
final Exception exception;
JSONArray broadcastData = null;
String indexData = null;
public UpResult(long resultingRevision, Exception exception) {
this.resultingRevision = resultingRevision;
this.exception = exception;
}
public UpResult(long resultingRevision, JSONArray broadcastData, String indexData) {
this.resultingRevision = resultingRevision;
this.exception = null;
this.broadcastData = broadcastData;
this.indexData = indexData;
}
@Override
public boolean isRejected() {
return exception != null;
}
public long getResultingRevision() {
return resultingRevision;
}
public JSONArray getBroadcastData() {
return broadcastData;
}
public String getIndexData() {
return indexData;
}
}
/**
* A subsequence of the delta history that can be extended in both directions.
*/
private class TransformDeltaCache {
private final DeltaIteratorProvider reverseDeltaIterator;
// Too bad ArrayDeque does not expose get(int) or perhaps even an
// unmodifiable subList(); we could use that rather than doing all this.
private final List<ChangeData<String>> onDiskDeltasReverse = Lists.newArrayList();
/** Deltas added during this transaction. */
private final List<ChangeData<String>> newDeltas = Lists.newArrayList();
/**
* A view over the reverse and forward deltas for conveniently allowing
* uniform access and traversal.
*/
private final List<ChangeData<String>> deltas = ConcatenatingList.of(
Lists.reverse(onDiskDeltasReverse), newDeltas);
private final long onDiskVersion;
/** @param reverseTailDeltas must start at onDiskVersion (and then go back). */
TransformDeltaCache(long onDiskVersion,
List<ChangeData<String>> reverseTailDeltas,
DeltaIteratorProvider reverseDeltaIterator) {
this.onDiskVersion = onDiskVersion;
onDiskDeltasReverse.addAll(reverseTailDeltas);
this.reverseDeltaIterator = reverseDeltaIterator;
}
private long minVersion() {
return onDiskVersion - onDiskDeltasReverse.size();
}
public List<ChangeData<String>> getNewDeltas() {
return Collections.unmodifiableList(newDeltas);
}
public void appendAll(List<ChangeData<String>> delta) {
newDeltas.addAll(delta);
}
private void ensureDeltasLoadedFrom(long version) throws PermanentFailure, RetryableFailure {
while (version < minVersion()) {
onDiskDeltasReverse.add(reverseDeltaIterator.get().next());
}
}
public List<ChangeData<String>> suffix(long fromVersion)
throws PermanentFailure, RetryableFailure {
ensureDeltasLoadedFrom(fromVersion);
return deltas.subList(Ints.checkedCast(fromVersion - minVersion()), deltas.size());
}
}
private class Tx implements UpdateTransaction<Update, UpResult> {
private final SlobId objectId;
private final CheckedTransaction tx;
private final MutationLog.Appender appender;
private final TransformDeltaCache deltaCache;
private final long onDiskVersion;
/**
* The most recent result. We choose it to be the "distinguished" request
* that carries extra info. See MutateResult.
*/
private UpResult lastResult = null;
Tx(SlobId objectId, CheckedTransaction tx) throws PermanentFailure, RetryableFailure {
this.objectId = objectId;
this.tx = tx;
MutationLog mutationLog = mutationLogFactory.create(tx, objectId);
MutationLog.AppenderAndCachedDeltas prepared = mutationLog.prepareAppender();
appender = prepared.getAppender();
onDiskVersion = appender.getStagedVersion();
deltaCache = new TransformDeltaCache(onDiskVersion,
prepared.getReverseDeltasRead(),
prepared.getReverseDeltaIteratorProvider());
}
@Override
public UpResult processUpdate(Update update)
throws BatchTooLargeException,
// TODO(danilatos): also throw BatchTooLargeException for updates that both
// 1) were not in the waiting items when the transaction started.
// 2) end up requiring an actual rpc to the datastore to fetch more data.
// But also: can use memcache to fetch more data.
RetryableFailure, PermanentFailure {
log.info("processUpdate " + update.toString(false));
Preconditions.checkArgument(objectId.equals(update.objectId),
"Object id %s does not match update %s", objectId, update);
// TODO(ohler): Randomly commit earlier to avoid deterministically running
// into transaction size or time limit; we estimate the size, but not
// accurately enough to rely on.
if (appender.getStagedVersion() - onDiskVersion >= MAX_BATCH_SIZE) {
throw new BatchTooLargeException("Batch max of " + MAX_BATCH_SIZE + " ops exceeded");
}
if (update.version > onDiskVersion) {
return logRejection(new UpResult(-1, new IllegalArgumentException(
"Update version " + update.version + " greater than " + onDiskVersion)));
}
long difference = appender.getStagedVersion() - update.version;
if (difference > MAX_TAIL_SIZE) {
log.info("Update too far in the past, out of date by " + difference);
// TODO(danilatos): Force client to retrieve history through other
// means, do the transform itself and then retry.
log.warning("TODO: Reject update too far in the past");
monitoring.incrementCounter("submitdelta-update-too-far-in-the-past");
}
log.info("Getting suffix..."); // Log on either side to time possible RPC.
List<ChangeData<String>> concurrent = deltaCache.suffix(update.version);
log.info("Got suffix of size " + concurrent.size());
// TODO(danilatos): Add op-serializing/deserializing methods to the model
// code, to avoid unnecessary deserialization when we have nothing to
// transform, and then eliminate this if-statement (just do the first
// branch unconditionally).
ImmutableList<ChangeData<String>> transformedChanges;
if (!concurrent.isEmpty()) {
log.info("processUpdate: transforming " + update.payloads.size() + " client changes"
+ " against " + concurrent.size() + " concurrent changes");
try {
transformedChanges = update.changes(model.transform(
update.changes(update.payloads), Collections.unmodifiableList(concurrent)));
} catch (ChangeRejected e) {
return logRejection(new UpResult(-1, e));
}
} else {
transformedChanges = update.changes(update.payloads);
log.info("processUpdate: not transforming");
}
// Stage payloads for writing.
try {
appender.appendAll(transformedChanges);
} catch (ChangeRejected e) {
return logRejection(new UpResult(-1, e));
}
deltaCache.appendAll(transformedChanges);
log.info("Ops successfully appended (staged for writing)");
return lastResult = new UpResult(appender.getStagedVersion(), null);
}
private UpResult logRejection(UpResult r) {
log.log(Level.WARNING, "Update rejected", r);
return r;
}
// TODO(danilatos): Update the update objects with transformed operations to
// avoid re-transforming what we've already transformed in case of a retry,
// once a thorough unit test framework for this code has been set up.
@Override
public void commit() throws RetryableFailure, PermanentFailure {
if (!appender.hasNewDeltas()) {
log.info("Nothing to commit?");
tx.rollback();
return;
}
appender.finish();
runPreCommit(tx, objectId, appender);
schedulePostCommit(tx, objectId, appender);
log.info("Committing...");
try {
tx.commit();
} catch (RetryableFailure e) {
log.log(Level.INFO, "RetryableFailure while committing mutation", e);
monitoring.incrementCounter("object-update-transaction-retryable-failure");
throw e;
} catch (PermanentFailure e) {
log.log(Level.INFO, "PermanentFailure while committing mutation", e);
monitoring.incrementCounter("object-update-transaction-permanent-failure");
throw e;
}
if (lastResult != null) {
List<ChangeData<String>> deltasToBroadcast = deltaCache.getNewDeltas();
JSONArray messages = new JSONArray();
for (int i = 0; i < deltasToBroadcast.size(); i++) {
try {
messages.put(i, ChangeDataSerializer.dataToClientJson(
deltasToBroadcast.get(i), onDiskVersion + i + 1));
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
lastResult.broadcastData = messages;
lastResult.indexData = appender.getIndexedHtml();
}
}
@Override
public void rollback() {
tx.rollback();
}
}
public void runPreCommit(CheckedTransaction tx, SlobId slobId, MutationLog.Appender appender)
throws PermanentFailure, RetryableFailure {
for (PreCommitAction action : preCommitActions) {
log.info("Calling pre-commit action " + action);
action.run(tx, slobId, appender.getStagedVersion(), appender.getStagedState());
}
}
public void schedulePostCommit(CheckedTransaction tx, SlobId slobId,
MutationLog.Appender appender) throws PermanentFailure, RetryableFailure {
postCommitActionScheduler.prepareCommit(
tx, slobId, appender.getStagedVersion(), appender.getStagedState());
}
private final SlobModel model;
private final MutationLogFactory mutationLogFactory;
private final CheckedDatastore datastore;
private final MonitoringVars monitoring;
private final Set<PreCommitAction> preCommitActions;
private final PostCommitActionScheduler postCommitActionScheduler;
// See commit ebb4736368b6d371a1bf5005541d96b88dcac504 for my failed attempt
// at using CacheBuilder. TODO(ohler): Figure out the right solution to this.
@SuppressWarnings("deprecation")
private final Map<SlobId, Processor> processors = new MapMaker()
.weakValues()
.makeComputingMap(new Function<SlobId, Processor>() {
@Override public Processor apply(final SlobId id) {
log.info("Creating new Processor for " + id);
return new Processor(
new TransactionFactory<UpResult, Tx>() {
@Override public Tx beginTransaction() throws RetryableFailure, PermanentFailure {
return new Tx(id, datastore.beginTransaction());
}
}, new RetryHelper());
}
});
@Inject
public LocalMutationProcessor(SlobModel model,
MutationLogFactory mutationLogFactory, CheckedDatastore datastore,
MonitoringVars monitoring,
Set<PreCommitAction> preCommitActions,
PostCommitActionScheduler postCommitActionScheduler) {
this.model = model;
this.mutationLogFactory = mutationLogFactory;
this.datastore = datastore;
this.monitoring = monitoring;
this.preCommitActions = preCommitActions;
this.postCommitActionScheduler = postCommitActionScheduler;
}
private String jsonBroadcastData(SlobId objectId, JSONArray broadcastData) {
try {
JSONObject obj = new JSONObject();
obj.put("id", objectId.getId());
obj.put("m", broadcastData);
return obj.toString();
} catch (JSONException e) {
throw new RuntimeException("Bad broadcast data: " + broadcastData, e);
}
}
public ServerMutateResponse mutateObject(ServerMutateRequest req) throws IOException {
SlobId objectId = new SlobId(req.getSession().getObjectId());
Preconditions.checkArgument(req.getVersion() >= 0, "Invalid version: %s", req.getVersion());
Preconditions.checkArgument(!req.getPayload().isEmpty(), "Empty payload list");
Update update = new Update(objectId,
new ClientId(req.getSession().getClientId()),
req.getVersion(),
req.getPayload());
log.info("mutateObject, update=" + update);
UpResult result;
try {
result = processors.get(objectId).processUpdate(update);
} catch (PermanentFailure e) {
throw new IOException(e);
}
if (result.isRejected()) {
throw new BadRequestException(result.exception);
}
ServerMutateResponse response = new ServerMutateResponseGsonImpl();
response.setResultingVersion(result.getResultingRevision());
response.setBroadcastData(jsonBroadcastData(objectId, result.getBroadcastData()));
response.setIndexData(result.getIndexData());
return response;
}
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
/**
* Thrown when access to an {@link SlobStore} object is denied.
*
* @author ohler@google.com (Christian Ohler)
*/
public class AccessDeniedException extends Exception {
private static final long serialVersionUID = 381349724431770197L;
public AccessDeniedException() {
}
public AccessDeniedException(String message) {
super(message);
}
public AccessDeniedException(Throwable cause) {
super(cause);
}
public AccessDeniedException(String message, Throwable cause) {
super(message, cause);
}
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.walkaround.slob.shared.MessageException;
import org.waveprotocol.wave.communication.gson.GsonException;
import org.waveprotocol.wave.communication.gson.GsonSerializable;
import org.waveprotocol.wave.communication.json.RawStringData;
/**
* Utilities for JSON protobuf handling based on GSON.
*
* @author piotrkaleta@google.com (Piotr Kaleta)
* @author ohler@google.com (Christian Ohler)
*/
public class GsonProto {
private GsonProto() {}
public enum JsonStrategy {
REGULAR, MULTISTAGE,
}
public static <T extends GsonSerializable> T fromGson(T gsonObj, String serialized)
throws MessageException {
Gson gson = new Gson();
JsonElement jsonElement = new JsonParser().parse(serialized);
try {
gsonObj.fromGson(jsonElement, gson, null);
return gsonObj;
} catch (RuntimeException e) {
// I've seen IllegalStateExceptions in JsonArray.getAsString().
throw new MessageException("Failed to parse " + gsonObj.getClass() + ": " + serialized, e);
} catch (GsonException e) {
throw new MessageException("Failed to parse " + gsonObj.getClass() + ": " + serialized, e);
}
}
public static String toJson(GsonSerializable message, JsonStrategy strategy) {
Gson gson = new Gson();
// TODO(piotrkaleta): Do we need multistage strategy at all?
switch (strategy) {
case REGULAR:
return gson.toJson(message.toGson(null, gson));
case MULTISTAGE:
RawStringData data = new RawStringData();
JsonElement rootElement = message.toGson(data, gson);
data.setBaseStringIndex(data.addString(gson.toJson(rootElement)));
return data.serialize();
default:
throw new AssertionError("Unknown JsonStrategy: " + strategy);
}
}
/**
* Helper method to turn Gson object into JSON representation
*
* @return String containing JSON representation of an object
*/
public static String toJson(GsonSerializable message) {
return toJson(message, JsonStrategy.REGULAR);
}
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
import com.google.walkaround.slob.shared.SlobId;
/**
* Thrown when the requested object is not found.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
// TODO(danilatos): Require object id in all constructors.
public class SlobNotFoundException extends Exception {
private static final long serialVersionUID = 605087702497587099L;
public SlobNotFoundException(SlobId id) {
super("Not found: " + id);
}
public SlobNotFoundException(String message, Throwable cause) {
super(message, cause);
}
public SlobNotFoundException(String message) {
super(message);
}
public SlobNotFoundException(Throwable cause) {
super(cause);
}
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.appengine.api.channel.ChannelFailureException;
import com.google.appengine.api.channel.ChannelMessage;
import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.memcache.Expiration;
import com.google.appengine.api.memcache.MemcacheService.SetPolicy;
import com.google.common.base.Objects;
import com.google.common.collect.Sets;
import com.google.inject.BindingAnnotation;
import com.google.inject.Inject;
import com.google.walkaround.slob.shared.ClientId;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.util.server.Util;
import com.google.walkaround.util.server.appengine.MemcacheTable;
import java.io.Serializable;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Router that connects client channels as listeners to objects in an m:n
* fashion, and provides the token required for channel set up.
*
* <p>
* Messages are not guaranteed to be delivered, nor are they guaranteed to be in
* order, nor is there any guaranteed about lack of duplicate messages. The
* message contents should provide enough information to allow clients to deal
* with these situations.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class SlobMessageRouter {
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface SlobChannelExpirationSeconds {}
public static class TooManyListenersException extends Exception {
private static final long serialVersionUID = 455819249880278222L;
public TooManyListenersException(String message, Throwable cause) {
super(message, cause);
}
public TooManyListenersException(String message) {
super(message);
}
public TooManyListenersException(Throwable cause) {
super(cause);
}
}
private static class ListenerAlreadyPresent extends Exception {
private static final long serialVersionUID = 144800949601544909L;
private final ListenerKey key;
private final ClientId clientId;
private ListenerAlreadyPresent(ListenerKey key, ClientId clientId) {
super(key + " " + clientId);
this.key = key;
this.clientId = clientId;
}
}
private static class ListenerKey implements Serializable {
private static final long serialVersionUID = 601407287266649008L;
private final SlobId id;
private final int listenerNum;
public ListenerKey(SlobId id, int listenerNum) {
this.id = checkNotNull(id, "Null id");
this.listenerNum = listenerNum;
}
public SlobId getId() {
return id;
}
public int getListenerNum() {
return listenerNum;
}
@Override public String toString() {
return "ListenerKey(" + id + ", " + listenerNum + ")";
}
@Override public final boolean equals(Object o) {
if (o == this) { return true; }
if (!(o instanceof ListenerKey)) { return false; }
ListenerKey other = (ListenerKey) o;
return listenerNum == other.listenerNum
&& Objects.equal(id, other.id);
}
@Override public final int hashCode() {
return Objects.hashCode(id, listenerNum);
}
}
private static final Logger log = Logger.getLogger(SlobMessageRouter.class.getName());
private static final int MAX_LISTENERS = 51;
private static final String LISTENER_MEMCACHE_TAG = "ORL";
private static final String CLIENTS_MEMCACHE_TAG = "ORC";
private final MemcacheTable<ListenerKey, ClientId> objectListeners;
private final MemcacheTable<ClientId, String> clientTokens;
private final ChannelService channelService;
private final int expirationSeconds;
@Inject
public SlobMessageRouter(MemcacheTable.Factory memcacheFactory, ChannelService channelService,
@SlobChannelExpirationSeconds int expirationSeconds) {
this.objectListeners = memcacheFactory.create(LISTENER_MEMCACHE_TAG);
this.clientTokens = memcacheFactory.create(CLIENTS_MEMCACHE_TAG);
this.channelService = channelService;
this.expirationSeconds = expirationSeconds;
}
/**
* Publishes messages to clients listening on an object.
*/
public void publishMessages(SlobId object, String jsonString) {
if (jsonString.length() > 8000) {
// Channel API has a limit of 32767 UTF-8 bytes. It's OK for us not to
// publish large messages; we can let clients poll. TODO(ohler): 8000 is
// probably overly conservative, make a better estimate.
log.warning(object + ": Message too large ("
+ jsonString.length() + " chars), not publishing: " + jsonString);
return;
} else {
log.info("Publishing " + object + " " + jsonString);
}
Map<?, ClientId> takenMappings = getMappings(object);
for (ClientId listener : takenMappings.values()) {
sendData(listener, jsonString);
}
}
/**
* Connects a client as a listener to an object. A client may listen to more
* than one object.
*
* <p>
* Returns the token the client should use to set up its browser channel. A
* client will only use one token, even if it is listening to multiple
* objects. The router keeps track of this, and will return the client's
* existing token if it already has one.
*/
public String connectListener(SlobId objectId, ClientId clientId)
throws TooManyListenersException {
log.info("Connecting " + clientId + " to " + objectId);
String channelToken;
int maxAttempts = 10;
for (int attempt = 0; attempt < maxAttempts; attempt++) {
boolean success;
try {
int freeId = getFreeKeyForListener(objectId, clientId);
assert freeId >= 0 && freeId < MAX_LISTENERS;
success = objectListeners.put(new ListenerKey(objectId, freeId), clientId,
Expiration.byDeltaSeconds(expirationSeconds),
SetPolicy.ADD_ONLY_IF_NOT_PRESENT);
if (success) {
log.info("Created new listener: " + clientId);
}
} catch (ListenerAlreadyPresent e) {
// This is just an expiry refresh, ideally we would rather not clobber
// a different listener in the unlikely event it got changed in this
// brief instant, but that doesn't matter.
objectListeners.put(e.key, e.clientId,
Expiration.byDeltaSeconds(expirationSeconds),
SetPolicy.SET_ALWAYS);
success = true;
log.info("Refreshed listener: " + e.clientId);
}
if (success) {
return tokenFor(clientId);
}
log.info("Failed to create listener, might retry...");
}
log.warning("Max attempts to set a listener exceeded");
throw new TooManyListenersException("Max attempts to set a listener exceeded");
}
private String tokenFor(ClientId clientId) {
String existing = clientTokens.get(clientId);
if (existing != null) {
log.info("Got existing token for client " + clientId + ": " + existing);
return existing;
}
// This might screw up a concurrent attempt to do the same thing but
// doesn't really matter.
String token = channelService.createChannel(clientId.getId());
clientTokens.put(clientId, token);
log.info("Got new token for client " + clientId + ": " + token);
return token;
}
private void sendData(ClientId clientId, String data) {
log.info("Sending to " + clientId + ", " + Util.abbrev(data, 50));
try {
channelService.sendMessage(new ChannelMessage(clientId.getId(), data));
} catch (ChannelFailureException e) {
// Channel service is best-effort anyway, so it's safe to discard the
// exception after taking note of it.
log.log(Level.SEVERE, "Channel service failed for " + clientId, e);
}
}
private int getFreeKeyForListener(SlobId object, ClientId clientId)
throws TooManyListenersException, ListenerAlreadyPresent {
Map<ListenerKey, ClientId> takenMappings = getMappings(object);
for (Map.Entry<ListenerKey, ClientId> entry : takenMappings.entrySet()) {
if (clientId.equals(entry.getValue())) {
throw new ListenerAlreadyPresent(entry.getKey(), entry.getValue());
}
}
// MAX_LISTENERS is small, and we need to iterate up to it anyway
// in getMappings()
for (int i = 0; i < MAX_LISTENERS; i++) {
if (!takenMappings.containsKey(new ListenerKey(object, i))) {
return i;
}
}
throw new TooManyListenersException(object + " has too many listeners");
}
private Map<ListenerKey, ClientId> getMappings(SlobId object) {
Set<ListenerKey> keys = Sets.newHashSet();
for (int i = 0; i < MAX_LISTENERS; i++) {
keys.add(new ListenerKey(object, i));
}
return objectListeners.getAll(keys);
}
}
| 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.walkaround.slob.server;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
import com.google.walkaround.slob.server.handler.PostCommitTaskHandler;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Guice annotation for a String that contains the URL served by
* {@link PostCommitTaskHandler}.
*
* @author ohler@google.com (Christian Ohler)
*/
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface PostCommitTaskUrl {}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
/**
* Thrown when the request to the object store was not valid. This is
* generally unrecoverable.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class InvalidStoreRequestException extends RuntimeException {
private static final long serialVersionUID = 568034814018982501L;
public InvalidStoreRequestException() {
}
public InvalidStoreRequestException(String message) {
super(message);
}
public InvalidStoreRequestException(Throwable cause) {
super(cause);
}
public InvalidStoreRequestException(String message, Throwable cause) {
super(message, cause);
}
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
import com.google.walkaround.slob.shared.SlobId;
/**
* Called in {@link SlobStore#mutateObject} after the object has changed.
*
* @author ohler@google.com (Christian Ohler)
*/
// TODO(ohler): Eliminate this; indexing should be done by adding a task queue
// task via PreCommitHook.
public interface PostMutateHook {
final PostMutateHook NO_OP = new PostMutateHook() {
@Override public void run(SlobId objectId, MutateResult result) {}
};
void run(SlobId objectId, MutateResult mutateResult);
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
import static com.google.walkaround.slob.server.StoreAccessChecker.WALKAROUND_TRUSTED_HEADER;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.appengine.api.backends.BackendService;
import com.google.appengine.api.memcache.Expiration;
import com.google.appengine.api.memcache.MemcacheService.SetPolicy;
import com.google.appengine.api.urlfetch.FetchOptions;
import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.common.base.Charsets;
import com.google.common.net.UriEscapers;
import com.google.inject.BindingAnnotation;
import com.google.inject.Inject;
import com.google.walkaround.proto.ServerMutateRequest;
import com.google.walkaround.proto.ServerMutateResponse;
import com.google.walkaround.proto.gson.ServerMutateResponseGsonImpl;
import com.google.walkaround.slob.shared.MessageException;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.util.server.MonitoringVars;
import com.google.walkaround.util.server.Util;
import com.google.walkaround.util.server.appengine.MemcacheTable;
import com.google.walkaround.util.server.auth.DigestUtils2.Secret;
import com.google.walkaround.util.server.servlet.TryAgainLaterException;
import com.google.walkaround.util.shared.RandomBase64Generator;
import org.waveprotocol.wave.communication.gson.GsonSerializable;
import org.waveprotocol.wave.model.util.Pair;
import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.net.URL;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Used by frontends to process mutations.
*
* Processes mutations by trying to forward them to a backend to do the actual
* work. Implements a best-effort affinity policy so that in general writes to
* the same object hit one backend. Falls back to writing on the frondend under
* certain circumstances.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class AffinityMutationProcessor {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(AffinityMutationProcessor.class.getName());
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface StoreBackendName {}
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface StoreBackendInstanceCount {}
private class PostRequest {
private final StringBuilder urlBuilder = new StringBuilder();
private final StringBuilder contentBuilder = new StringBuilder();
void urlParam(String key, String value) {
urlBuilder.append((urlBuilder.length() == 0 ? "?" : "&") + key + "=" + urlEncode(value));
}
void postParam(String key, String value) {
contentBuilder.append(key + "=" + urlEncode(value) + "&");
}
/**
* @return the response body as a String.
* @throws IOException for 500 or above or general connection problems.
* @throws InvalidStoreRequestException for any response code not 200.
*/
String send(String base) throws IOException {
URL url = new URL(base + urlBuilder.toString());
HTTPRequest req = new HTTPRequest(url, HTTPMethod.POST, getFetchOptions());
// TODO(ohler): use multipart/form-data for efficiency
req.setHeader(new HTTPHeader("Content-Type", "application/x-www-form-urlencoded"));
req.setHeader(new HTTPHeader(WALKAROUND_TRUSTED_HEADER, secret.getHexData()));
// NOTE(danilatos): Appengine will send 503 if the backend is at the
// max number of concurrent requests. We might come up with a use for
// handling this error code specifically. For now, we didn't go through
// the code to make sure that all other overload situations also manifest
// themselves as 503 rather than random exceptions that turn into 500s.
// Therefore, the code in this class treats all 5xx responses as an
// indication of possible overload.
req.setHeader(new HTTPHeader("X-AppEngine-FailFast", "true"));
req.setPayload(contentBuilder.toString().getBytes(Charsets.UTF_8));
log.info("Sending to " + url);
String ret = fetch(req);
log.info("Request completed");
return ret;
}
private FetchOptions getFetchOptions() {
FetchOptions options = FetchOptions.Builder
.disallowTruncate()
.doNotFollowRedirects();
return options;
}
private String describeResponse(HTTPResponse resp) {
StringBuilder b = new StringBuilder(resp.getResponseCode()
+ " with " + resp.getContent().length + " bytes of content");
for (HTTPHeader h : resp.getHeaders()) {
b.append("\n" + h.getName() + ": " + h.getValue());
}
b.append("\n" + new String(resp.getContent(), Charsets.UTF_8));
return "" + b;
}
private String fetch(HTTPRequest req) throws IOException {
HTTPResponse response = fetchService.fetch(req);
int responseCode = response.getResponseCode();
if (responseCode >= 300 && responseCode < 400) {
throw new RuntimeException("Unexpected redirect for url " + req.getURL()
+ ": " + describeResponse(response));
}
byte[] rawResponseBody = response.getContent();
String responseBody;
if (rawResponseBody == null) {
responseBody = "";
} else {
responseBody = new String(rawResponseBody, Charsets.UTF_8);
}
if (responseCode != 200) {
String msg = req.getURL() + " gave response code " + responseCode
+ ", body: " + responseBody;
if (responseCode >= 500) {
throw new IOException(msg);
} else {
throw new InvalidStoreRequestException(msg);
}
}
return responseBody;
}
private String urlEncode(String s) {
return UriEscapers.uriQueryStringEscaper(false).escape(s);
}
}
private static final String MEMCACHE_TAG = "OSM";
// TODO(danilatos): Make these flags.
private static final int AFFINITY_MIN_EXPIRATION_SECONDS = 30;
private static final int AFFINITY_MAX_EXPIRATION_SECONDS = 45;
private static final int AFFINITY_EXPIRATION_SPREAD_SECONDS =
AFFINITY_MAX_EXPIRATION_SECONDS - AFFINITY_MIN_EXPIRATION_SECONDS;
private final Random random;
private final RandomBase64Generator random64;
private final URLFetchService fetchService;
private final BackendService backends;
private final LocalMutationProcessor localProcessor;
private final MemcacheTable<SlobId, Integer> objectServerMappings;
private final Secret secret;
private final int numStoreServers;
private final String storeServerName;
private final MonitoringVars monitoring;
@Inject
public AffinityMutationProcessor(
Random random,
RandomBase64Generator random64,
URLFetchService fetchService,
BackendService backends,
LocalMutationProcessor localProcessor,
MemcacheTable.Factory memcacheFactory,
Secret secret,
@StoreBackendInstanceCount int numStoreServers,
@StoreBackendName String storeServer,
MonitoringVars monitoring) {
this.random = random;
this.random64 = random64;
this.fetchService = fetchService;
this.backends = backends;
this.localProcessor = localProcessor;
this.objectServerMappings = memcacheFactory.create(MEMCACHE_TAG);
this.secret = secret;
this.numStoreServers = numStoreServers;
this.storeServerName = storeServer;
this.monitoring = monitoring;
}
public ServerMutateResponse mutateObject(ServerMutateRequest req) throws IOException {
// TODO(danilatos): Document strategy.
ServerMutateResponse result;
SlobId objectId = new SlobId(req.getSession().getObjectId());
if (numStoreServers == 0) {
monitoring.incrementCounter("affinity-backends-disabled");
result = localProcessor.mutateObject(req);
} else {
Pair<Boolean, Integer> info = serverFor(objectId);
if (info == null) {
log.warning("Could not establish a mapping, falling back to processing on frontend");
monitoring.incrementCounter("affinity-could-not-establish-mapping");
// It's unlikely there is a backend owning this object for us to interfere with,
// so attempting to process on the frontend is better than nothing.
result = localProcessor.mutateObject(req);
} else {
try {
// Attempt normal situation - process on the backend to which
// the object has affinity.
int serverId = info.getSecond();
result = processOnBackend(serverId, req);
monitoring.incrementCounter("affinity-processed-on-backend");
} catch (IOException e) { // "500" type errors.
boolean wasMapped = info.getFirst();
if (wasMapped) {
// Maybe the particular object is under high load.
// In such a case we don't know we won't be making matters worse
// by choosing another server or doing it locally, because we
// may increase contention on the object's entity group and slow
// things down further. (While one object won't make much difference,
// this policy applies on aggregate). By getting the client to
// back off, we degrade smoothly - and if it's just that server
// that's under load, the situation will rectify itself after
// the memcache association expires.
log.log(Level.WARNING, "Backend threw exception, getting client to back off", e);
monitoring.incrementCounter("affinity-backend-overloaded-backing-off");
throw new TryAgainLaterException("Client back off due to load", e);
} else {
// Maybe we're under-provisioned in terms of store servers.
// In this case, where the object was not mapped, it's far less
// likely that doing the work locally would contend with a backend
// trying to process mutations for that object. So we do the
// work locally to ensure progress. We also remove the mapping
// so that if it's just that server that was under load, the next
// attempt to write might choose a different backend and have
// more success. If all backends are over-loaded, then we degrade
// gracefully by processing the surplus writes on frontends for
// objects that fail to "claim" a mapping.
log.log(Level.WARNING, "Backend threw exception, attempting mutation on frontend", e);
monitoring.incrementCounter("affinity-backend-overloaded-processing-locally");
// Remove mapping and process locally.
objectServerMappings.delete(objectId);
result = localProcessor.mutateObject(req);
}
}
}
}
return result;
}
/**
* Returns and maybe creates a mapping to a server for the given object id.
*
* @return the mapped server, and true if that mapping already existed, false
* if it was created by this method.
*
* WARNING: if a mapping could not be established, returns null.
*/
@Nullable
private Pair<Boolean, Integer> serverFor(SlobId objectId) {
boolean wasMapped;
int serverId;
Integer maybeServerId = objectServerMappings.get(objectId);
if (maybeServerId != null) {
wasMapped = true;
serverId = maybeServerId;
monitoring.incrementCounter("affinity-mapping-found");
} else {
int newServerId = random.nextInt(numStoreServers);
int expiration = AFFINITY_MIN_EXPIRATION_SECONDS
+ random.nextInt(AFFINITY_EXPIRATION_SPREAD_SECONDS);
log.info("No mapping for " + objectId + ", generated " + newServerId +
", expiration " + expiration);
boolean putSucceeded = objectServerMappings.put(objectId, newServerId,
Expiration.byDeltaSeconds(expiration),
SetPolicy.ADD_ONLY_IF_NOT_PRESENT);
if (putSucceeded) {
serverId = newServerId;
wasMapped = false;
monitoring.incrementCounter("affinity-mapping-generated");
} else {
log.warning("Mapping was generated concurrently");
maybeServerId = objectServerMappings.get(objectId);
if (maybeServerId != null) {
serverId = maybeServerId;
wasMapped = true;
monitoring.incrementCounter("affinity-mapping-generated-but-overwritten");
} else {
log.warning("Concurrently generated mapping promptly disappeared!");
monitoring.incrementCounter("affinity-mapping-generated-but-lost");
return null;
}
}
}
return Pair.of(wasMapped, serverId);
}
private ServerMutateResponse processOnBackend(int serverId, ServerMutateRequest req)
throws IOException {
String base = "http://" + backends.getBackendAddress(storeServerName, serverId);
// For debugging, to match up requests in the logs.
String requestId = random64.next(10) + "____" + req.getSession().getObjectId();
log.info("Using backend " + base + " for requestId " + requestId);
PostRequest post = new PostRequest();
post.urlParam("requestId", requestId);
post.postParam("req", GsonProto.toJson((GsonSerializable) req));
String response = post.send(Util.pathCat(base, "store/mutate"));
if (!response.startsWith("OK")) {
throw new RuntimeException("Backend gave junk " + response);
}
try {
return GsonProto.fromGson(new ServerMutateResponseGsonImpl(),
response.substring(2));
} catch (MessageException e) {
throw new RuntimeException("Backend gave incompatible JSON: " + response, e);
}
}
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
import com.google.common.base.Preconditions;
import com.google.walkaround.slob.shared.ChangeData;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.logging.Logger;
/**
* @author danilatos@google.com (Daniel Danilatos)
*/
public class ChangeDataSerializer {
private ChangeDataSerializer() {}
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(ChangeDataSerializer.class.getName());
/** The largest integer that can be represented losslessly by a double */
public static final long MAX_DOUBLE_INTEGER = 1L << 52 - 1;
public static JSONObject dataToClientJson(ChangeData<String> data, long resultingRevision) {
Preconditions.checkArgument(resultingRevision <= MAX_DOUBLE_INTEGER,
"Resulting revision %s is too large", resultingRevision);
// Assume payload is JSON, and parse it to avoid nested json.
// TODO(danilatos): Consider using ChangeData<JSONObject> instead.
// The reason I haven't done it yet is because it's not immutable,
// and also for reasons described in ChangeData.
JSONObject payloadJson;
try {
payloadJson = new JSONObject(data.getPayload());
} catch (JSONException e) {
throw new IllegalArgumentException("Invalid payload for " + data, e);
}
JSONObject json = new JSONObject();
try {
Preconditions.checkArgument(resultingRevision >= 0, "invalid rev %s", resultingRevision);
json.put("revision", resultingRevision);
long sanityCheck = json.getLong("revision");
if (sanityCheck != resultingRevision) {
throw new AssertionError("resultingRevision " + resultingRevision
+ " not losslessly represented in JSON, got back " + sanityCheck);
}
json.put("sid", data.getClientId().getId());
json.put("op", payloadJson);
return json;
} catch (JSONException e) {
throw new Error(e);
}
}
}
| 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.walkaround.slob.server;
import com.google.appengine.api.datastore.Key;
import com.google.walkaround.slob.server.MutationLog.MutationLogFactory;
import com.google.walkaround.slob.shared.SlobId;
/**
* Offers access to various classes that operate on a slob type.
*
* @author ohler@google.com (Christian Ohler)
*/
public interface SlobFacilities {
SlobStore getSlobStore();
MutationLogFactory getMutationLogFactory();
LocalMutationProcessor getLocalMutationProcessor();
String getRootEntityKind();
Key makeRootEntityKey(SlobId slobId);
SlobId parseRootEntityKey(Key key);
PostCommitActionScheduler getPostCommitActionScheduler();
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
import com.google.walkaround.slob.shared.SlobId;
/**
* Checks if access to a given object is permitted. The accessing user is
* implicit.
*
* @author ohler@google.com (Christian Ohler)
*/
public interface AccessChecker {
void checkCanRead(SlobId objectId) throws AccessDeniedException;
void checkCanModify(SlobId objectId) throws AccessDeniedException;
void checkCanCreate(SlobId objectId) throws AccessDeniedException;
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
import com.google.walkaround.proto.ServerMutateRequest;
import com.google.walkaround.proto.ServerMutateResponse;
import java.io.IOException;
/**
* Processes an {@link SlobStore} mutation, either locally, or by forwarding
* the request to another server. The request must already be authorized.
*
* @author ohler@google.com (Christian Ohler)
*/
public interface MutationProcessor {
ServerMutateResponse mutateObject(ServerMutateRequest request) throws IOException;
}
| 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.walkaround.slob.server;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Guice annotation. Post-commit actions are throttled to run only roughly once
* every this many millis per slob.
*
* @author ohler@google.com (Christian Ohler)
*/
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface PostCommitActionIntervalMillis {}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
import com.google.walkaround.slob.shared.SlobId;
import java.io.IOException;
import javax.annotation.Nullable;
/**
* @author danilatos@google.com (Daniel Danilatos)
*/
// TODO(ohler): eliminate this class.
public interface SlobManager {
public static final class SlobIndexUpdate {
@Nullable private final String indexedHtml;
@Nullable private final Boolean viewed;
/**
* @param indexedHtml optionally update the indexed html
* @param viewed optionally update the viewed state
*/
public SlobIndexUpdate(@Nullable String indexedHtml, @Nullable Boolean viewed) {
this.indexedHtml = indexedHtml;
this.viewed = viewed;
}
@Override public String toString() {
return "SlobIndexUpdate(" + (indexedHtml != null ? indexedHtml.length() : "null") + ","
+ viewed + ")";
}
@Nullable public String getIndexedHtml() {
return indexedHtml;
}
@Nullable public Boolean getViewed() {
return viewed;
}
}
void update(SlobId objectId, SlobIndexUpdate update) throws IOException;
}
| 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.walkaround.slob.server.handler;
import com.google.inject.Inject;
import com.google.walkaround.slob.server.PostCommitAction;
import com.google.walkaround.slob.server.SlobStoreSelector;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import com.google.walkaround.util.server.servlet.BadRequestException;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Task queue handler that processes {@link PostCommitAction}s.
*
* @author ohler@google.com (Christian Ohler)
*/
public class PostCommitTaskHandler extends AbstractHandler {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(PostCommitTaskHandler.class.getName());
public static String STORE_TYPE_PARAM = "store_type";
public static String SLOB_ID_PARAM = "slob_id";
@Inject SlobStoreSelector storeSelector;
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
log.info(this + ": doPost()");
if (req.getHeader("X-AppEngine-QueueName") == null) {
throw new BadRequestException();
}
String storeType = requireParameter(req, STORE_TYPE_PARAM);
SlobId slobId = new SlobId(requireParameter(req, SLOB_ID_PARAM));
storeSelector.get(storeType).getPostCommitActionScheduler().taskInvoked(slobId);
}
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
import javax.annotation.Nullable;
/**
* Result of sending a mutation to an object in the object store.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public final class MutateResult {
private final long resultingVersion;
@Nullable private final String indexData;
public MutateResult(long resultingVersion, @Nullable String indexData) {
this.resultingVersion = resultingVersion;
this.indexData = indexData;
}
public long getResultingVersion() {
return resultingVersion;
}
@Nullable public String getIndexData() {
return indexData;
}
@Override public String toString() {
return "MutateResult(" + resultingVersion + ")";
}
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Guice annotation for the String that will be used as the object snapshot entity kind.
*
* @author ohler@google.com (Christian Ohler)
*/
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface SlobSnapshotEntityKind {}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Guice annotation for the String that will be used as the entity kind for
* dummy, data-less entities written to the datastore to ensure serialization by
* triggering concurrency exceptions in concurrent operations.
*
* @author ohler@google.com (Christian Ohler)
*/
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface SlobSynchronizationEntityKind {}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
/**
* @author ohler@google.com (Christian Ohler)
*/
public class SlobAlreadyExistsException extends Exception {
private static final long serialVersionUID = 234235844730282653L;
public SlobAlreadyExistsException() {
}
public SlobAlreadyExistsException(String message) {
super(message);
}
public SlobAlreadyExistsException(Throwable cause) {
super(cause);
}
public SlobAlreadyExistsException(String message, Throwable cause) {
super(message, cause);
}
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.slob.shared.SlobModel.ReadableSlob;
import com.google.walkaround.util.server.RetryHelper.PermanentFailure;
import com.google.walkaround.util.server.RetryHelper.RetryableFailure;
import com.google.walkaround.util.server.appengine.CheckedDatastore.CheckedTransaction;
/**
* Reliably called some time after {@link SlobStore#mutateObject} commits a
* sequence of changes to an object. Should be idempotent.
*
* @author ohler@google.com (Christian Ohler)
*/
public interface PostCommitAction {
/** Run immediately after commit, with high likelihood, only once. */
void unreliableImmediatePostCommit(SlobId slobId, long resultingVersion, ReadableSlob resultingState);
/** Run some time after the commit, guaranteed, possibly multiple times. */
void reliableDelayedPostCommit(SlobId slobId);
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Guice annotation for the String that will be used as the object root entity kind.
*
* @author ohler@google.com (Christian Ohler)
*/
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface SlobRootEntityKind {}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.walkaround.util.server.servlet.BadRequestException;
import java.util.Map;
/**
* Maps "store type" strings (= root entity kind) to the corresponding SlobFacilities.
*
* @author ohler@google.com (Christian Ohler)
*/
public class SlobStoreSelector {
private final Map<String, Provider<SlobFacilities>> facilities;
@Inject
public SlobStoreSelector(Map<String, Provider<SlobFacilities>> facilities) {
this.facilities = facilities;
}
public SlobFacilities get(String storeType) {
Provider<SlobFacilities> provider = facilities.get(storeType);
if (provider != null) {
return provider.get();
}
throw new BadRequestException("Unknown store type: " + storeType);
}
}
| Java |
/*
* Copyright 2011 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.walkaround.slob.server;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.google.appengine.api.datastore.Text;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import com.google.walkaround.slob.shared.ChangeData;
import com.google.walkaround.slob.shared.ChangeRejected;
import com.google.walkaround.slob.shared.ClientId;
import com.google.walkaround.slob.shared.InvalidSnapshot;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.slob.shared.SlobModel;
import com.google.walkaround.slob.shared.SlobModel.ReadableSlob;
import com.google.walkaround.slob.shared.StateAndVersion;
import com.google.walkaround.util.server.RetryHelper.PermanentFailure;
import com.google.walkaround.util.server.RetryHelper.RetryableFailure;
import com.google.walkaround.util.server.appengine.CheckedDatastore.CheckedIterator;
import com.google.walkaround.util.server.appengine.CheckedDatastore.CheckedTransaction;
import com.google.walkaround.util.server.appengine.DatastoreUtil;
import com.google.walkaround.util.shared.Assert;
import org.waveprotocol.wave.model.util.Pair;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Functionality for traversing and appending to the mutation log.
*
* Use of only this class for mutating the log guarantees no corruption will
* occur.
*
* XXX(danilatos): Not necessarily thread safe, should only be used in a
* single-threaded fashion but let's make it thread safe anyway just in case...
* (better yet, add assertions that it's used only from one thread, so that we
* notice when it's not)
*
* @author danilatos@google.com (Daniel Danilatos)
* @author ohler@google.com (Christian Ohler)
*/
public class MutationLog {
public interface MutationLogFactory {
// TODO(danilatos): Rename this method to "get" to avoid connotations of
// creating objects. Do this any time there's low chance of conflicts.
MutationLog create(CheckedTransaction tx, SlobId objectId);
}
private static class CacheEntry {
private final long version;
@Nullable private final String snapshot;
private final long mostRecentSnapshotBytes;
private final long totalDeltaBytesSinceSnapshot;
public CacheEntry(long version,
@Nullable String snapshot,
long mostRecentSnapshotBytes,
long totalDeltaBytesSinceSnapshot) {
this.version = version;
this.snapshot = snapshot;
this.mostRecentSnapshotBytes = mostRecentSnapshotBytes;
this.totalDeltaBytesSinceSnapshot = totalDeltaBytesSinceSnapshot;
}
public long getVersion() {
return version;
}
@Nullable public String getSnapshot() {
return snapshot;
}
public long getMostRecentSnapshotBytes() {
return mostRecentSnapshotBytes;
}
public long getTotalDeltaBytesSinceSnapshot() {
return totalDeltaBytesSinceSnapshot;
}
@Override public String toString() {
return getClass().getSimpleName() + "("
+ version + ", "
+ snapshot + ", "
+ mostRecentSnapshotBytes + ", "
+ totalDeltaBytesSinceSnapshot
+ ")";
}
}
// Singleton so that we have a per-process cache. TODO(ohler): Verify how this interacts with
// scoping of the private store modules.
@Singleton
static class StateCache {
// Key is a pair of root entity kind (= store type) and slob id.
private final Map<Pair<String, SlobId>, CacheEntry> currentStates;
@Inject StateCache(@SlobLocalCacheExpirationMillis int expirationMillis) {
// See commit ebb4736368b6d371a1bf5005541d96b88dcac504 for my failed attempt
// at using CacheBuilder. TODO(ohler): Figure out the right solution to this.
@SuppressWarnings("deprecation")
Map<Pair<String, SlobId>, CacheEntry> currentStates = new MapMaker()
.softValues()
.expireAfterAccess(expirationMillis, TimeUnit.MILLISECONDS)
.makeMap();
this.currentStates = currentStates;
}
}
private static final Logger log = Logger.getLogger(MutationLog.class.getName());
@VisibleForTesting static final String DELTA_OP_PROPERTY = "op";
@VisibleForTesting static final String DELTA_CLIENT_ID_PROPERTY = "sid";
@VisibleForTesting static final String SNAPSHOT_DATA_PROPERTY = "Data";
private static final String METADATA_PROPERTY = "Metadata";
// Datastore does not allow ids to be 0.
private static long versionFromDeltaId(long id) {
return id - 1;
}
private static long deltaIdFromVersion(long version) {
return version + 1;
}
private static class DeltaEntry {
private final SlobId objectId;
private final long version;
private final ChangeData<String> data;
DeltaEntry(SlobId objectId, long version, ChangeData<String> data) {
this.objectId = objectId;
this.version = version;
this.data = data;
}
long getResultingVersion() {
return version + 1;
}
@Override
public String toString() {
return "DeltaEntry(" + objectId + ", " + version + ", " + data + ")";
}
}
private static class SnapshotEntry {
private final SlobId objectId;
private final long version;
private final String snapshot;
SnapshotEntry(SlobId objectId, long version, String snapshot) {
this.objectId = objectId;
this.version = version;
this.snapshot = snapshot;
}
@Override
public String toString() {
return "SnapshotEntry(" + objectId + ", " + version + ", " + snapshot + ")";
}
}
static Key makeRootEntityKey(String entityGroupKind, SlobId objectId) {
Key key = KeyFactory.createKey(entityGroupKind, objectId.getId());
Assert.check(parseRootEntityKey(entityGroupKind, key).equals(objectId),
"Mismatch: %s, %s", objectId, key);
return key;
}
static SlobId parseRootEntityKey(String entityGroupKind, Key key) {
Preconditions.checkArgument(entityGroupKind.equals(key.getKind()),
"Key doesn't have kind %s: %s", entityGroupKind, key);
return new SlobId(key.getName());
}
private Key makeRootEntityKey(SlobId slobId) {
return makeRootEntityKey(entityGroupKind, slobId);
}
private Key makeDeltaKey(SlobId objectId, long version) {
return KeyFactory.createKey(
makeRootEntityKey(objectId),
deltaEntityKind,
deltaIdFromVersion(version));
}
private Key makeSnapshotKey(SlobId objectId, long version) {
return KeyFactory.createKey(
makeRootEntityKey(objectId),
snapshotEntityKind,
version);
}
private Key makeDeltaKey(DeltaEntry e) {
return makeDeltaKey(e.objectId, e.version);
}
private Key makeSnapshotKey(SnapshotEntry e) {
return makeSnapshotKey(e.objectId, e.version);
}
private static long estimateSizeBytes(Key key) {
// It's not documented whether and how the representation returned by
// keyToString() relates to the representation that the API limits are based
// on; but in any case, it should be good enough for our estimate.
long web64Size = KeyFactory.keyToString(key).length();
// Base-64 strings have 6 bits per character, thus the ratio is 6/8 or 3/4.
// Divide by 4 first to avoid overflow. The base-64 string should be padded
// to a length that is a multiple of 4, so there is no rounding error. (If
// it's not padded, our estimate will be off; but that is tolerable, too.)
return (web64Size / 4) * 3;
}
private long estimateSizeBytes(DeltaEntry deltaEntry) {
return estimateSizeBytes(makeDeltaKey(deltaEntry))
+ DELTA_CLIENT_ID_PROPERTY.length() + deltaEntry.data.getClientId().getId().length()
+ DELTA_OP_PROPERTY.length() + deltaEntry.data.getPayload().length();
}
private long estimateSizeBytes(SnapshotEntry snapshotEntry) {
return estimateSizeBytes(makeSnapshotKey(snapshotEntry))
+ SNAPSHOT_DATA_PROPERTY.length() + snapshotEntry.snapshot.length();
}
public interface DeltaEntityConverter {
ChangeData<String> convert(Entity entity);
}
public static class DefaultDeltaEntityConverter implements DeltaEntityConverter {
@Override public ChangeData<String> convert(Entity entity) {
return new ChangeData<String>(
new ClientId(
DatastoreUtil.getExistingProperty(entity, DELTA_CLIENT_ID_PROPERTY, String.class)),
DatastoreUtil.getExistingProperty(entity, DELTA_OP_PROPERTY, Text.class).getValue());
}
}
private DeltaEntry parseDelta(Entity entity) {
SlobId slobId = new SlobId(entity.getKey().getParent().getName());
long version = versionFromDeltaId(entity.getKey().getId());
return new DeltaEntry(slobId, version, deltaEntityConverter.convert(entity));
}
private static void populateDeltaEntity(DeltaEntry in, Entity out) {
DatastoreUtil.setNonNullUnindexedProperty(out, DELTA_CLIENT_ID_PROPERTY,
in.data.getClientId().getId());
DatastoreUtil.setNonNullUnindexedProperty(out, DELTA_OP_PROPERTY,
new Text(in.data.getPayload()));
}
private static SnapshotEntry parseSnapshot(Entity e) {
SlobId id = new SlobId(e.getKey().getParent().getName());
long version = e.getKey().getId();
return new SnapshotEntry(id, version,
DatastoreUtil.getExistingProperty(e, SNAPSHOT_DATA_PROPERTY, Text.class).getValue());
}
private static void populateSnapshotEntity(SnapshotEntry in, Entity out) {
DatastoreUtil.setNonNullUnindexedProperty(out, SNAPSHOT_DATA_PROPERTY, new Text(in.snapshot));
}
/**
* An iterator over a datastore delta result list.
*
* Can be forward or reverse.
*
* The peek methods should be used in conjunction with
* {@link DeltaIterator#hasNext()} since they will throw
* {@code NoSuchElementException} if the end of the sequence is reached.
*/
public class DeltaIterator {
private final CheckedIterator it;
private final boolean forward;
private long previousResultingVersion;
@Nullable private DeltaEntry peeked = null;
public DeltaIterator(CheckedIterator it, boolean forward) {
this.it = Preconditions.checkNotNull(it, "Null it");
this.forward = forward;
previousResultingVersion = -1;
}
public boolean hasNext() throws PermanentFailure, RetryableFailure {
return peeked != null || it.hasNext();
}
DeltaEntry peekEntry() throws PermanentFailure, RetryableFailure {
if (peeked == null) {
// Let it.next() throw if there is no next.
peeked = parseDelta(it.next());
checkVersion(peeked);
}
return peeked;
}
DeltaEntry nextEntry() throws PermanentFailure, RetryableFailure {
DeltaEntry result = peekEntry();
peeked = null;
return result;
}
public ChangeData<String> peek() throws PermanentFailure, RetryableFailure {
return peekEntry().data;
}
public ChangeData<String> next() throws PermanentFailure, RetryableFailure {
return nextEntry().data;
}
public boolean isForward() {
return forward;
}
private void checkVersion(DeltaEntry delta) {
if (previousResultingVersion != -1) {
long expectedResultingVersion = previousResultingVersion + (forward ? 1 : -1);
Assert.check(delta.getResultingVersion() == expectedResultingVersion,
"%s: Expected version %s, got %s",
this, expectedResultingVersion, delta.getResultingVersion());
}
}
@Override public String toString() {
return "DeltaIterator(" + (forward ? "forward" : "reverse")
+ ", " + previousResultingVersion + ")";
}
}
/**
* Extends the log by additional deltas. Automatically takes snapshots as
* needed.
*
* Deltas and snapshots are staged in memory and added to the underlying
* transaction only when {@link Appender#finish()} is called.
*/
public class Appender {
private final StateAndVersion state;
private final List<DeltaEntry> stagedDeltaEntries = Lists.newArrayList();
private final List<SnapshotEntry> stagedSnapshotEntries = Lists.newArrayList();
private long estimatedBytesStaged = 0;
private long mostRecentSnapshotBytes;
private long totalDeltaBytesSinceSnapshot;
private boolean finished = false;
private Appender(StateAndVersion state,
long mostRecentSnapshotBytes,
long totalDeltaBytesSinceSnapshot) {
this.state = state;
this.mostRecentSnapshotBytes = mostRecentSnapshotBytes;
this.totalDeltaBytesSinceSnapshot = totalDeltaBytesSinceSnapshot;
}
private void checkNotFinished() {
Preconditions.checkState(!finished, "%s: already finished", this);
}
/**
* Stages a delta for writing, verifying that it is valid (applies cleanly).
*/
public void append(ChangeData<String> delta) throws ChangeRejected {
checkNotFinished();
appendAll(ImmutableList.of(delta));
}
/**
* Stage deltas for writing, verifying that they are valid (apply cleanly).
* Will append whatever prefix of {@deltas} is valid before throwing
* {@link ChangeRejected}.
*/
public void appendAll(List<ChangeData<String>> deltas) throws ChangeRejected {
checkNotFinished();
if (deltas.isEmpty()) {
// For now, this is a no-op; if we want this to potentially append a
// snapshot, we'll need a justification for that.
return;
}
deltas = ImmutableList.copyOf(deltas);
for (ChangeData<String> delta : deltas) {
long oldVersion = state.getVersion();
state.apply(delta);
DeltaEntry deltaEntry = new DeltaEntry(objectId, oldVersion,
new ChangeData<String>(delta.getClientId(), delta.getPayload()));
stagedDeltaEntries.add(deltaEntry);
long thisDeltaBytes = estimateSizeBytes(deltaEntry);
estimatedBytesStaged += thisDeltaBytes;
totalDeltaBytesSinceSnapshot += thisDeltaBytes;
}
// TODO(ohler): Avoid computing the snapshot every time since this is
// costly. Add a size estimation to slob instead. We need this anyway to
// implement size limits.
SnapshotEntry snapshotEntry = new SnapshotEntry(
objectId, state.getVersion(), state.getState().snapshot());
long snapshotBytes = estimateSizeBytes(snapshotEntry);
log.info("Object now at version " + state.getVersion() + "; snapshotBytes=" + snapshotBytes
+ ", mostRecentSnapshotBytes=" + mostRecentSnapshotBytes
+ ", totalDeltaBytesSinceSnapshot=" + totalDeltaBytesSinceSnapshot);
// To reconstruct the object's snapshot S at the current version, we will
// need to read the most recent snapshot P followed by a sequence of
// deltas D. To keep the amount of data required for this reconstruction
// within a constant factor of |S| (the size of S), we write S to disk if
// k * |S| < |P| + |D|, for some constant k.
//
// Computing the snapshot size |S| currently takes linear time, so when
// appending a sequence of deltas, we only do it once at the end, to avoid
// taking quadratic time. This is not a problem with small batches of
// operations from clients, but can make imports time out.
//
// TODO(ohler): Provide bound on disk space consumption.
//
// TODO(ohler): This formula assumes that reading & reconstructing a
// snapshot has the same cost per byte as reading & applying a delta.
// That's probably not true. The cost of applying a delta may not even be
// linear in the size of that delta (and the same is true for
// reconstructing from a snapshot); this depends on the model. We should
// allow for models to influence when to take snapshots, perhaps by
// letting the model provide a size metric for deltas and snapshots
// instead of using bytes, or by measuring actual computation time if we
// can do that reliably. It would be best to make it impossible for
// models to cause quadratic disk space consumption, though.
final long k = 2;
if (k * snapshotBytes < mostRecentSnapshotBytes + totalDeltaBytesSinceSnapshot) {
log.info("Adding snapshot");
stagedSnapshotEntries.add(snapshotEntry);
mostRecentSnapshotBytes = snapshotBytes;
totalDeltaBytesSinceSnapshot = 0;
estimatedBytesStaged += snapshotBytes;
}
}
/**
* A rough estimate of the total bytes currently staged to be written. This
* may be subject to inaccuracies such as counting Java's UTF-16 characters
* in strings as one byte each (actual encoding that the API limits are
* based on is probably UTF-8) and only counting raw payloads without taking
* metadata, encoding overhead, or indexing overhead into account.
*/
public long estimatedBytesStaged() {
return estimatedBytesStaged;
}
public long getStagedVersion() {
return state.getVersion();
}
public ReadableSlob getStagedState() {
return state.getState();
}
public boolean hasNewDeltas() {
return !stagedDeltaEntries.isEmpty();
}
/**
* Returns the index data of the model at head state (including staged mutations).
*/
// TODO(ohler): Add a generic task queue hook to MutationLog and
// SlobStore, and use that to move indexing into an asynchronous task
// queue task. That would make indexing reliable and avoid polluting this
// API with SlobManager concerns like indexing.
public String getIndexedHtml() {
return state.getState().getIndexedHtml();
}
/**
* Calls {@code put()} on all staged deltas and snapshots, etc.
*/
public void finish() throws PermanentFailure, RetryableFailure {
checkNotFinished();
finished = true;
log.info("Flushing " + stagedDeltaEntries.size() + " deltas and "
+ stagedSnapshotEntries.size() + " snapshots");
put(tx, stagedDeltaEntries, stagedSnapshotEntries);
tx.runAfterCommit(new Runnable() {
@Override public void run() {
stateCache.currentStates.put(Pair.of(entityGroupKind, objectId),
new CacheEntry(state.getVersion(), state.getState().snapshot(),
mostRecentSnapshotBytes, totalDeltaBytesSinceSnapshot));
}
});
stagedDeltaEntries.clear();
stagedSnapshotEntries.clear();
estimatedBytesStaged = 0;
}
}
private final String entityGroupKind;
private final String deltaEntityKind;
private final String snapshotEntityKind;
private final DeltaEntityConverter deltaEntityConverter;
private final CheckedTransaction tx;
private final SlobId objectId;
private final SlobModel model;
private final StateCache stateCache;
@AssistedInject
public MutationLog(@SlobRootEntityKind String entityGroupKind,
@SlobDeltaEntityKind String deltaEntityKind,
@SlobSnapshotEntityKind String snapshotEntityKind,
DeltaEntityConverter deltaEntityConverter,
@Assisted CheckedTransaction tx, @Assisted SlobId objectId,
SlobModel model,
StateCache stateCache) {
this.entityGroupKind = entityGroupKind;
this.deltaEntityKind = deltaEntityKind;
this.snapshotEntityKind = snapshotEntityKind;
this.deltaEntityConverter = deltaEntityConverter;
this.tx = Preconditions.checkNotNull(tx, "Null tx");
this.objectId = Preconditions.checkNotNull(objectId, "Null objectId");
this.model = Preconditions.checkNotNull(model, "Null model");
this.stateCache = stateCache;
}
/** @see #forwardHistory(long, Long, FetchOptions) */
public DeltaIterator forwardHistory(long minVersion, @Nullable Long maxVersion)
throws PermanentFailure, RetryableFailure {
return forwardHistory(minVersion, maxVersion, FetchOptions.Builder.withDefaults());
}
/**
* Returns an iterator over the specified version range of the mutation log,
* in a forwards direction.
*
* @param maxVersion null to end with the final delta in the mutation log.
*/
public DeltaIterator forwardHistory(long minVersion, @Nullable Long maxVersion,
FetchOptions fetchOptions) throws PermanentFailure, RetryableFailure {
return getDeltaIterator(minVersion, maxVersion, fetchOptions, true);
}
/** @see #reverseHistory(long, Long, FetchOptions) */
public DeltaIterator reverseHistory(long minVersion, @Nullable Long maxVersion)
throws PermanentFailure, RetryableFailure {
return reverseHistory(minVersion, maxVersion, FetchOptions.Builder.withDefaults());
}
/**
* Returns an iterator over the specified version range of the mutation log,
* in a backwards direction.
*
* @param maxVersion null to begin with the final delta in the mutation log.
*/
public DeltaIterator reverseHistory(long minVersion, @Nullable Long maxVersion,
FetchOptions fetchOptions) throws PermanentFailure, RetryableFailure {
return getDeltaIterator(minVersion, maxVersion, fetchOptions, false);
}
/**
* Returns the current version of the object.
*/
public long getVersion() throws PermanentFailure, RetryableFailure {
DeltaIterator it = reverseHistory(0, null, FetchOptions.Builder.withLimit(1));
if (!it.hasNext()) {
return 0;
}
return it.nextEntry().getResultingVersion();
}
static interface DeltaIteratorProvider {
DeltaIterator get() throws PermanentFailure, RetryableFailure;
}
private static DeltaIteratorProvider makeProvider(final DeltaIterator x) {
checkNotNull(x, "Null x");
return new DeltaIteratorProvider() {
@Override public DeltaIterator get() {
return x;
}
};
}
/**
* Tuple of values returned by {@link #prepareAppender()}.
*/
public static class AppenderAndCachedDeltas {
private final Appender appender;
private final List<ChangeData<String>> reverseDeltasRead;
private final DeltaIteratorProvider reverseDeltaIteratorProvider;
public AppenderAndCachedDeltas(Appender appender,
List<ChangeData<String>> reverseDeltasRead,
DeltaIteratorProvider reverseDeltaIteratorProvider) {
Preconditions.checkNotNull(appender, "Null appender");
Preconditions.checkNotNull(reverseDeltasRead, "Null reverseDeltasRead");
Preconditions.checkNotNull(reverseDeltaIteratorProvider, "Null reverseDeltaIteratorProvider");
this.appender = appender;
this.reverseDeltasRead = reverseDeltasRead;
this.reverseDeltaIteratorProvider = reverseDeltaIteratorProvider;
}
public Appender getAppender() {
return appender;
}
public List<ChangeData<String>> getReverseDeltasRead() {
return reverseDeltasRead;
}
public DeltaIteratorProvider getReverseDeltaIteratorProvider()
throws PermanentFailure, RetryableFailure {
return reverseDeltaIteratorProvider;
}
@Override public String toString() {
return "AppenderAndCachedDeltas("
+ appender + ", "
+ reverseDeltasRead + ", "
+ reverseDeltaIteratorProvider
+ ")";
}
}
@Nullable private Entity getDeltaEntity(long version) throws RetryableFailure, PermanentFailure {
return tx.get(makeDeltaKey(objectId, version));
}
private void checkDeltaDoesNotExist(long version) throws RetryableFailure, PermanentFailure {
// This check is not necessary but let's be paranoid.
// TODO(danilatos): Make this async and check the result on flush() to
// improve latency. Or, make an informed decision to remove it.
Entity existing = getDeltaEntity(version);
Assert.check(existing == null,
"Datastore fail? Found unexpected delta: %s, %s, %s",
objectId, version, existing);
}
/**
* Creates an {@link Appender} for this mutation log and returns it together
* with some by-products. The by-products can be useful to callers who need
* data from the datastore that overlaps with what was needed to create the
* {@code Appender}, to avoid redundant datastore reads.
*/
public AppenderAndCachedDeltas prepareAppender() throws PermanentFailure, RetryableFailure {
Pair<String, SlobId> cacheKey = Pair.of(entityGroupKind, objectId);
CacheEntry cached = stateCache.currentStates.get(cacheKey);
if (cached != null) {
long cachedVersion = cached.getVersion();
// We need to check if a delta with version cachedVersion is present; that
// would indicate that our cache is out of date. Since we're paranoid, we
// additionally check that cachedVersion-1 is present (it always has to
// be).
//
// After writing the code to use a key-only query here, I found
// http://code.google.com/appengine/docs/billing.html#Billable_Resource_Unit_Cost
// which implies that the cost of this is
//
// 1 "Read" + 1 "Small" + (no transform needed ? 0 : 1 "Read" + # reverse
// deltas needed * 1 "Read")
//
// while the cost of using a reverse delta iterator (not key-only, so that
// we can reuse it and pass it into AppenderAndCachedDeltas below) and
// always reading the first delta entity would be
//
// 2 "Read" + (no transform needed ? 0 : (# reverse deltas needed - 1) * 1 "Read")
//
// where a "Read" has a cost of 7 units, a "Small" has a cost of 1 unit.
//
// Essentially, the variant implemented here saves 6 units when no deltas
// are needed for transform, but pays an extra 8 otherwise.
//
// When cached != null but another writer interfered, we also pay an extra
// 8 units compared to sharing the same iterator.
//
// It's not clear which of these situation is going to be common and which
// is not, and whether the cost is worth worrying aboung. I happened to
// implement it this way first and only found that billing page later, so
// I'll leave it for now, even though the code is very slighly more
// complicated. If we ever introduce a delta cache, that would make the
// case of having no deltas to read for transform more common, and would
// (presumably) make sharing the iterator harder, so this code would be a
// better starting point for that.
boolean cacheValid;
if (cachedVersion == 0) {
cacheValid = getDeltaEntity(0L) == null;
} else {
CheckedIterator deltaKeys = getDeltaEntityIterator(cachedVersion - 1, cachedVersion + 1,
FetchOptions.Builder.withChunkSize(2).limit(2).prefetchSize(2), true, true);
if (!deltaKeys.hasNext()) {
throw new RuntimeException("Missing data: Delta " + cachedVersion
+ " not found: " + deltaKeys);
}
deltaKeys.next();
cacheValid = !deltaKeys.hasNext();
}
if (cacheValid) {
log.info("MutationLog cache: Constructing appender based on cached slob version "
+ cachedVersion);
return new AppenderAndCachedDeltas(
new Appender(createObject(cached.getVersion(), cached.getSnapshot()),
cached.getMostRecentSnapshotBytes(), cached.getTotalDeltaBytesSinceSnapshot()),
ImmutableList.<ChangeData<String>>of(),
new DeltaIteratorProvider() {
DeltaIterator i = null;
@Override public DeltaIterator get() throws PermanentFailure, RetryableFailure {
if (i == null) {
i = getDeltaIterator(0, null, FetchOptions.Builder.withDefaults(), false);
}
return i;
}
});
} else {
log.info("MutationLog cache: Another writer interfered (cached slob version was "
+ cachedVersion + ")");
stateCache.currentStates.remove(cacheKey);
}
} else {
log.info("MutationLog cache: No slob version cached");
}
return prepareAppenderSlowCase();
}
private AppenderAndCachedDeltas prepareAppenderSlowCase()
throws PermanentFailure, RetryableFailure {
DeltaIterator deltaIterator = getDeltaIterator(
0, null, FetchOptions.Builder.withDefaults(), false);
if (!deltaIterator.hasNext()) {
log.info("Prepared appender at version 0");
checkDeltaDoesNotExist(0);
return new AppenderAndCachedDeltas(
new Appender(createObject(null), 0, 0),
ImmutableList.<ChangeData<String>>of(), makeProvider(deltaIterator));
} else {
SnapshotEntry snapshotEntry = getSnapshotEntryAtOrBefore(null);
StateAndVersion state = createObject(snapshotEntry);
long snapshotVersion = state.getVersion();
long snapshotBytes = snapshotEntry == null ? 0 : estimateSizeBytes(snapshotEntry);
// Read deltas between snapshot and current version. Since we determine
// the current version by reading the first delta (in our reverse
// iterator), we always read at least one delta even if none are needed to
// reconstruct the current version.
DeltaEntry finalDelta = deltaIterator.nextEntry();
long currentVersion = finalDelta.getResultingVersion();
if (currentVersion == snapshotVersion) {
// We read a delta but it precedes the snapshot. It still has to go
// into deltasRead in our AppenderAndCachedDeltas to ensure that there
// is no gap between deltasRead and reverseIterator.
log.info("Prepared appender; snapshotVersion=currentVersion=" + currentVersion);
checkDeltaDoesNotExist(snapshotVersion);
return new AppenderAndCachedDeltas(
new Appender(state, snapshotBytes, 0),
ImmutableList.of(finalDelta.data), makeProvider(deltaIterator));
} else {
// We need to apply the delta and perhaps others. Collect them.
ImmutableList.Builder<ChangeData<String>> deltaAccu = ImmutableList.builder();
deltaAccu.add(finalDelta.data);
long totalDeltaBytesSinceSnapshot = estimateSizeBytes(finalDelta);
{
DeltaEntry delta = finalDelta;
while (delta.version != snapshotVersion) {
delta = deltaIterator.nextEntry();
deltaAccu.add(delta.data);
totalDeltaBytesSinceSnapshot += estimateSizeBytes(delta);
}
}
ImmutableList<ChangeData<String>> reverseDeltas = deltaAccu.build();
// Now iterate forward and apply the deltas.
for (ChangeData<String> delta : Lists.reverse(reverseDeltas)) {
try {
state.apply(delta);
} catch (ChangeRejected e) {
throw new RuntimeException("Corrupt snapshot or delta history: "
+ objectId + " rejected delta " + delta + ": " + state);
}
}
log.info("Prepared appender; snapshotVersion=" + snapshotVersion
+ ", " + reverseDeltas.size() + " deltas");
checkDeltaDoesNotExist(state.getVersion());
return new AppenderAndCachedDeltas(
new Appender(state, snapshotBytes, totalDeltaBytesSinceSnapshot),
reverseDeltas, makeProvider(deltaIterator));
}
}
}
private CheckedIterator getDeltaEntityIterator(long startVersion, @Nullable Long endVersion,
FetchOptions fetchOptions, boolean forward, boolean keysOnly)
throws PermanentFailure, RetryableFailure {
checkRange(startVersion, endVersion);
if (endVersion != null && startVersion == endVersion) {
return CheckedIterator.EMPTY;
}
Query q = new Query(deltaEntityKind)
.setAncestor(makeRootEntityKey(objectId))
.addFilter(Entity.KEY_RESERVED_PROPERTY,
FilterOperator.GREATER_THAN_OR_EQUAL, makeDeltaKey(objectId, startVersion))
.addSort(Entity.KEY_RESERVED_PROPERTY,
forward ? SortDirection.ASCENDING : SortDirection.DESCENDING);
if (endVersion != null) {
q.addFilter(Entity.KEY_RESERVED_PROPERTY,
FilterOperator.LESS_THAN, makeDeltaKey(objectId, endVersion));
}
if (keysOnly) {
q.setKeysOnly();
}
return tx.prepare(q).asIterator(fetchOptions);
}
private DeltaIterator getDeltaIterator(long startVersion, @Nullable Long endVersion,
FetchOptions fetchOptions, boolean forward)
throws PermanentFailure, RetryableFailure {
return new DeltaIterator(
getDeltaEntityIterator(startVersion, endVersion, fetchOptions, forward, false),
forward);
}
/**
* Reconstructs the object at the specified version (current version if null).
*/
public StateAndVersion reconstruct(@Nullable Long atVersion)
throws PermanentFailure, RetryableFailure {
checkRange(atVersion, null);
StateAndVersion state = getSnapshottedState(atVersion);
long startVersion = state.getVersion();
Assert.check(atVersion == null || startVersion <= atVersion);
DeltaIterator it = forwardHistory(startVersion, atVersion);
while (it.hasNext()) {
ChangeData<String> delta = it.next();
try {
state.apply(delta);
} catch (ChangeRejected e) {
throw new PermanentFailure(
"Corrupt snapshot or delta history " + objectId + " @" + state.getVersion(), e);
}
}
if (atVersion != null && state.getVersion() < atVersion) {
throw new RuntimeException("Object max version is " + state.getVersion()
+ ", requested " + atVersion);
}
log.info("Reconstructed requested version " + atVersion
+ " from snapshot at " + startVersion
+ " followed by " + (state.getVersion() - startVersion) + " deltas");
return state;
}
private void put(CheckedTransaction tx,
List<DeltaEntry> newDeltas, List<SnapshotEntry> newSnapshots)
throws PermanentFailure, RetryableFailure {
Preconditions.checkNotNull(newDeltas, "null newEntries");
Preconditions.checkNotNull(newSnapshots, "null newSnapshots");
List<Entity> entities = Lists.newArrayListWithCapacity(newDeltas.size() + newSnapshots.size());
for (DeltaEntry entry : newDeltas) {
Key key = makeDeltaKey(entry);
Entity newEntity = new Entity(key);
populateDeltaEntity(entry, newEntity);
parseDelta(newEntity); // Verify it parses with no exceptions.
entities.add(newEntity);
}
for (SnapshotEntry entry : newSnapshots) {
Key key = makeSnapshotKey(entry);
Entity newEntity = new Entity(key);
populateSnapshotEntity(entry, newEntity);
parseSnapshot(newEntity); // Verify it parses with no exceptions.
entities.add(newEntity);
}
tx.put(entities);
}
@Nullable private SnapshotEntry getSnapshotEntryAtOrBefore(@Nullable Long atOrBeforeVersion)
throws RetryableFailure, PermanentFailure {
Query q = new Query(snapshotEntityKind)
.setAncestor(makeRootEntityKey(objectId))
.addSort(Entity.KEY_RESERVED_PROPERTY, SortDirection.DESCENDING);
if (atOrBeforeVersion != null) {
q = q.addFilter(Entity.KEY_RESERVED_PROPERTY, FilterOperator.LESS_THAN_OR_EQUAL,
makeSnapshotKey(objectId, atOrBeforeVersion));
}
Entity e = tx.prepare(q).getFirstResult();
log.info("query " + q + " returned first result " + e);
return e == null ? null : parseSnapshot(e);
}
private StateAndVersion createObject(long version, @Nullable String snapshot) {
try {
return new StateAndVersion(model.create(snapshot), version);
} catch (InvalidSnapshot e) {
throw new RuntimeException("Could not create model from snapshot at version " + version
+ ": " + snapshot, e);
}
}
private StateAndVersion createObject(@Nullable SnapshotEntry entry) {
if (entry == null) {
return createObject(0, null);
} else {
return createObject(entry.version, entry.snapshot);
}
}
/**
* Constructs a model object from the snapshot with the highest version less
* than or equal to atOrBeforeVersion.
*
* @param atOrBeforeVersion null for current version
*/
public StateAndVersion getSnapshottedState(@Nullable Long atOrBeforeVersion)
throws PermanentFailure, RetryableFailure {
return createObject(getSnapshotEntryAtOrBefore(atOrBeforeVersion));
}
private void checkRange(@Nullable Long startVersion, @Nullable Long endVersion) {
if (startVersion == null) {
Preconditions.checkArgument(endVersion == null,
"startVersion == null implies endVersion == null, not %s", endVersion);
} else {
Preconditions.checkArgument(startVersion >= 0 &&
(endVersion == null || startVersion <= endVersion),
"Invalid range requested (%s to %s)", startVersion, endVersion);
// I doubt this would really happen, but...
Assert.check(endVersion == null || (endVersion - startVersion <= Integer.MAX_VALUE),
"Range too large: %s to %s", startVersion, endVersion);
}
}
// TODO(ohler): eliminate; PreCommitHook should be enough
@Nullable public String getMetadata() throws RetryableFailure, PermanentFailure {
Key key = makeRootEntityKey(objectId);
Entity entity = tx.get(key);
@Nullable String result = entity == null ? null
: DatastoreUtil.getExistingProperty(entity, METADATA_PROPERTY, Text.class).getValue();
log.info("Got " + result);
return result;
}
// TODO(ohler): eliminate; PreCommitHook should be enough
public void putMetadata(String metadata) throws RetryableFailure, PermanentFailure {
Entity e = new Entity(makeRootEntityKey(objectId));
DatastoreUtil.setNonNullUnindexedProperty(e, METADATA_PROPERTY, new Text(metadata));
log.info("Writing metadata: " + metadata);
tx.put(e);
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.client.log;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JsonUtils;
import com.google.gwt.xhr.client.XMLHttpRequest;
import com.google.walkaround.util.client.log.Logs.Handler;
import com.google.walkaround.util.client.log.Logs.Level;
/**
* A log handler that reports fatal logs to the server, and tees off warning
* logs to its subclass.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class ErrorReportingLogHandler implements Handler {
private boolean firstReport = true;
private final String errorReportUrl;
public ErrorReportingLogHandler(String errorReportUrl) {
this.errorReportUrl = errorReportUrl;
}
@Override
public boolean canReceive() {
return true;
}
@Override
public void receiveEntry(
int num, double timestamp, String stream, Level level, Object[] objects, Throwable t) {
if (level.compareTo(Level.SEVERE) <= 0) {
onSevere(stream);
report(timestamp, stream, level, objects, t);
}
}
/**
* Notifies a subclass of a severe log event on a stream.
*/
protected void onSevere(String stream) {
}
void report(double timestamp, String streamName, Level level, Object[] objects, Throwable t) {
// TODO(danilatos): Use a JsoView to construct and then serialize, rather
// than string builder, unless it's too slow (might even be faster).
StringBuilder sb = new StringBuilder();
sb.append("{\"strongName\" : ");
sb.append(escape(GWT.getPermutationStrongName()));
sb.append(",\"timestamp\" : ");
sb.append("" + (long) timestamp);
sb.append(",\"stream\" : ");
sb.append(escape(streamName));
sb.append(",\"level\" : ");
sb.append(escape(level.name()));
// Stacktrace info of the first exception found, if any
if (t != null) {
sb.append(",\"exception\" : ");
buildExceptionJson(sb, t);
}
sb.append(",\"objects\" : [");
boolean needsComma = false;
for (Object o : objects) {
if (needsComma) {
sb.append(",");
} else {
needsComma = true;
}
sb.append(escape(o != null ? o.toString() : "(null)"));
}
sb.append("]}");
String jsonData = sb.toString();
XMLHttpRequest xhr = XMLHttpRequest.create();
xhr.open("POST", errorReportUrl + "?firstReport=" + firstReport);
firstReport = false;
xhr.send(jsonData);
}
public void buildExceptionJson(StringBuilder sb, Throwable t) {
sb.append("{\"name\" : ");
sb.append(escape(t.getClass().getName()));
sb.append(",\"message\" : ");
sb.append(escape(t.getMessage()));
sb.append(",\"stackTrace\" : [");
boolean needsComma = false;
for (StackTraceElement e : t.getStackTrace()) {
if (needsComma) {
sb.append(",");
} else {
needsComma = true;
}
sb.append(escape(e.getMethodName()));
}
sb.append("]");
if (t.getCause() != null) {
sb.append(",\"cause\" : ");
buildExceptionJson(sb, t.getCause());
}
sb.append("}");
}
String escape(String unescaped) {
// + "" to avoid null
return JsonUtils.escapeValue(unescaped != null ? unescaped : "(null)");
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.client.log;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.StyleElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.DoubleClickEvent;
import com.google.gwt.event.dom.client.DoubleClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.walkaround.util.client.log.Logs.Level;
import org.waveprotocol.wave.client.widget.common.ImplPanel;
import org.waveprotocol.wave.model.util.CollectionUtils;
import org.waveprotocol.wave.model.util.ReadableStringMap.ProcV;
import org.waveprotocol.wave.model.util.StringMap;
import java.util.Date;
import java.util.EnumMap;
/**
* Handler for pretty printing log events in the DOM. Can be turned on and off.
* For debugging convenience, when it's turned on, it renders old entries that
* were logged before it was active.
*
* @author danilatos@google.com (Daniel Danilatos)
* @author hearnden@google.com (David Hearnden)
*/
public final class LogPanel extends Composite implements Logs.Handler {
/**
* Focuses an element in a schedule-finally command. When it eventually runs, it
* only focuses the most recently chosen element.
*/
private static final class Focuser implements ScheduledCommand {
private Element toFocus;
Focuser() {
}
void focusLater(Element e) {
if (toFocus == null) {
Scheduler.get().scheduleFinally(this);
}
toFocus = e;
}
@Override
public final void execute() {
toFocus.scrollIntoView();
toFocus = null;
}
}
//
// Standard 40 lines of GWT per-component boilerplate. This is required in
// order to stop GWT from injecting its own style element (at the wrong
// time, and without revealing access to it) for the CssResource.
//
interface Resources extends ClientBundle {
@Source("LogPanel.css")
Css css();
}
interface Css extends CssResource {
// Strict mode forces declaration of every class, even those used only by
// the UiBinder template.
String self();
String entries();
String header();
String button();
String control();
String enabled();
String disabled();
String level();
String stream();
String debug();
String info();
String warning();
String severe();
String item();
}
@UiField(provided = true)
static final Css css = GWT.<Resources>create(Resources.class).css();
interface Binder extends UiBinder<ImplPanel, LogPanel> {
}
private static final Binder BINDER = GWT.create(Binder.class);
//
// Interesting code starts below.
//
/**
* A button that controls filtering of some dimension of log entries.
*
* Each filter button synthesizes an associated CSS rule of the form:
* <dl>
* <dd>.hideFoo .foo { display: none; }</dd>
* </dl>
* for some dimension foo (e.g., a log level, or a stream).
*/
static class FilterButton extends Label implements ClickHandler {
/** Element to which filtering classes are added/removed. */
private final Element itemContainer;
/** CSS class to toggle on the container ({@code .hideFoo} in example). */
private final String containerClass;
/** CSS class of items affected by this rule (@code .foo} in example). */
private final String itemClass;
/** True when this filter is not hiding entries. */
private boolean allow = true;
FilterButton(DoubleClickHandler superSelect,
Element itemContainer,
String containerClass,
String itemClass,
String label,
String buttonClass) {
super(label);
this.itemContainer = itemContainer;
this.itemClass = itemClass;
this.containerClass = containerClass;
setStyleName(LogPanel.css.button() + " " + LogPanel.css.enabled() + " " + buttonClass);
addClickHandler(this);
if (superSelect != null) {
addDoubleClickHandler(superSelect);
}
}
@Override
public void onClick(ClickEvent event) {
setAllow(!allow);
}
void setAllow(boolean allow) {
if (this.allow != allow) {
if (allow) {
getElement().replaceClassName(LogPanel.css.disabled(), LogPanel.css.enabled());
itemContainer.removeClassName(containerClass);
} else {
getElement().replaceClassName(LogPanel.css.enabled(), LogPanel.css.disabled());
itemContainer.addClassName(containerClass);
}
this.allow = allow;
}
}
/** @return the class to apply to items controlled by this filter. */
public String getItemClass() {
return itemClass;
}
/** @return the CSS rule that makes this filter work. */
public String getCssRule() {
return "." + containerClass + " ." + itemClass + " {display:none;}";
}
}
/** Maximum number of DOM entries. Recycling occurs after this. */
private static final int MAX_ENTRIES = 3000;
/**
* Prefixes for stream and level filtering CSS classes. When a filter class is
* applied to the entries element, they hide entries that match the filter.
*/
private static final String STREAM_FILTER_PREFIX = "w-hs-";
private static final String LEVEL_FILTER_PREFIX = "w-hl-";
/** Pretty labels for printing levels. Designed for fixed-width output. */
private static final EnumMap<Level, String> LABELS = new EnumMap<Level, String>(Level.class);
static {
// All labels have equal size.
LABELS.put(Level.INFO, "INFO ");
LABELS.put(Level.DEBUG, "DEBUG ");
LABELS.put(Level.WARNING, "WARN ");
LABELS.put(Level.SEVERE, "SEVERE");
assert LABELS.size() == Level.values().length;
}
/** CSS classes for log levels. */
private static final EnumMap<Level, String> LEVEL_CLASSES =
new EnumMap<Level, String>(Level.class);
static {
LEVEL_CLASSES.put(Level.DEBUG, css.debug());
LEVEL_CLASSES.put(Level.INFO, css.info());
LEVEL_CLASSES.put(Level.WARNING, css.warning());
LEVEL_CLASSES.put(Level.SEVERE, css.severe());
assert LEVEL_CLASSES.size() == Level.values().length;
}
@UiField
ImplPanel self;
@UiField
Element play;
@UiField
Element clear;
@UiField
Element levelsContainer;
@UiField
Element streamsContainer;
@UiField
Element entries;
/** Log being handled. */
private final Logs log;
/** Buttons that disable particular levels. */
private final EnumMap<Level, FilterButton> levelFilters =
new EnumMap<Level, FilterButton>(Level.class);
/** Buttons that disable particular streams. */
private final StringMap<FilterButton> streamFilters = CollectionUtils.createStringMap();
/** Style element holding filter rules. */
private final StyleElement style = Document.get().createStyleElement();
/** Thing that brings the most recent log entry into view. */
private final Focuser focuser = new Focuser();
/** True if this panel is creating DOM for logs. Does not mean visible. */
private boolean active;
/** Index into the monotonic log history of the most recently printed log. */
private int upTo;
/** Number of entries in the DOM, constrained by {@link #MAX_ENTRIES}. */
private int numEntries;
private LogPanel(Logs log) {
this.log = log;
initWidget(BINDER.createAndBindUi(this));
// Add filter buttons. Global filter, then log-level filters.
StringBuilder rules = new StringBuilder();
rules.append(css.getText());
for (final Level level : Level.values()) {
String itemClass = LEVEL_CLASSES.get(level);
String containerClass = LEVEL_FILTER_PREFIX + itemClass;
FilterButton levelFilter = new FilterButton(new DoubleClickHandler() {
@Override
public void onDoubleClick(DoubleClickEvent event) {
enableOnlyMoreImportantLevels(level);
}
}, entries, containerClass, itemClass, level.name(), css.level());
levelFilters.put(level, levelFilter);
self.add(levelFilter, levelsContainer);
rules.append(levelFilter.getCssRule());
}
// Inject style.
style.setInnerText(rules.toString());
Document.get().getBody().appendChild(style);
setActive(true);
}
/**
* Creates a log panel.
*
* @param log log to observe
*/
public static LogPanel create(Logs log) {
LogPanel panel = new LogPanel(log);
panel.setActive(true);
return panel;
}
/**
* Creates a log panel, bringing attention to the severe logs of a particular
* stream.
*/
public static LogPanel createOnStream(Logs log, final String stream) {
LogPanel panel = create(log);
panel.enableOnlyMoreImportantLevels(Level.SEVERE);
panel.enableOnlyOneStream(stream);
return panel;
}
/** Activates/deactivates this handler. */
private void setActive(boolean active) {
boolean wasActive = this.active;
this.active = active;
if (!wasActive && active) {
log.pushEntries(upTo, this);
}
}
private void enableOnlyOneStream(final String selected) {
streamFilters.each(new ProcV<FilterButton>() {
@Override
public void apply(String stream, FilterButton filter) {
filter.setAllow(stream.equals(selected));
}
});
}
private void enableOnlyMoreImportantLevels(Level limit) {
for (Level level : Level.values()) {
levelFilters.get(level).setAllow(level.compareTo(limit) <= 0);
}
}
/**
* Gets the filter for a stream, creating one if one does not already exist.
*/
private FilterButton getStreamFilter(final String stream) {
FilterButton filter = streamFilters.get(stream);
if (filter == null) {
// Just in case a user can cause a stream to be called "'><script
// src='evil.js'></script><pre '", we only use safe values for CSS
// classes. There's no need for the class names to be human readable.
int streamId = streamFilters.countEntries();
String itemClass = "w-s-" + streamId;
String containerClass = STREAM_FILTER_PREFIX + streamId;
filter = new FilterButton(new DoubleClickHandler() {
@Override
public void onDoubleClick(DoubleClickEvent event) {
enableOnlyOneStream(stream);
}
}, entries, containerClass, itemClass, stream, css.stream());
self.add(filter, streamsContainer);
streamFilters.put(stream, filter);
// Replace stylesheet to make the new filter work.
style.setInnerText(style.getInnerText() + filter.getCssRule());
}
return filter;
}
@UiHandler("self")
void handleClick(ClickEvent e) {
Element target = e.getNativeEvent().getEventTarget().cast();
if (play.equals(target)) {
if (active) {
setActive(false);
play.setInnerText("Resume");
} else {
setActive(true);
play.setInnerText("Pause");
}
} else if (clear.equals(target)) {
entries.setInnerHTML("");
}
}
//
// LogHandler.
//
@Override
public boolean canReceive() {
return active;
}
@Override
public void receiveEntry(int num,
double timestamp,
String stream,
Level level,
Object[] objects,
Throwable ex) {
StringBuilder b = new StringBuilder();
b.append(DateTimeFormat.getFormat("HH:mm:ss.SSS").format(new Date((long) timestamp)) + " "
+ LABELS.get(level) + " (" + stream + "): ");
for (Object o : objects) {
if (o instanceof Throwable) {
printStackTrace((Throwable) o, b);
} else {
b.append(o != null ? o.toString() : "(null)");
}
}
Element pre;
if (numEntries < MAX_ENTRIES) {
pre = Document.get().createPreElement();
numEntries++;
} else {
pre = entries.getFirstChildElement();
}
String streamClass = getStreamFilter(stream).getItemClass();
String levelClass = LEVEL_CLASSES.get(level);
pre.setClassName(css.item() + " " + streamClass + " " + levelClass);
pre.setInnerText(b.toString());
entries.appendChild(pre);
focuser.focusLater(pre);
upTo = num + 1;
}
/**
* Prints a stack trace as text. The output is intended to be placed in a
* <pre> element, so no HTML markup is used.
*/
private static void printStackTrace(Throwable t, StringBuilder out) {
while (t != null) {
out.append(t.getClass().getName() + ": " + t.getLocalizedMessage() + "\n");
StackTraceElement[] elts = t.getStackTrace();
for (int i = 0; i < elts.length; i++) {
out.append(" at " + elts[i].getClassName() + "." + elts[i].getMethodName() + "("
+ elts[i].getFileName() + ":" + elts[i].getLineNumber() + ")\n");
}
t = t.getCause();
if (t != null) {
out.append("Caused by: ");
}
}
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.client.log;
import com.google.gwt.event.shared.UmbrellaException;
import com.google.gwt.user.client.Window;
import org.waveprotocol.wave.client.scheduler.Scheduler;
import org.waveprotocol.wave.client.scheduler.SchedulerInstance;
import org.waveprotocol.wave.client.scheduler.TimerService;
import org.waveprotocol.wave.model.util.CollectionUtils;
import java.util.Collection;
/**
* Client logging utility that supports lazy handlers, retention of a certain
* amount of historical log entries, and two dimensions of filtering (streams
* and levels).
*
* The implementation is designed to be efficient when expensive log rendering
* is turned off, by avoiding unnecessary object creation. Handlers are
* asynchronously notified that log events are available, and may choose to
* ignore them (if they are inactive) or have all events pushed to them.
*
* The {@link Logs.Log} interface omits the stream name in its interface,
* because it is intended to be a simple wrapper with the stream name curried in
* for convenience, as generally each application component will use a single
* stream name.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class Logs {
public enum Level {
/** An unrecoverable error, the application state may be corrupted */
// NOTE(ohler): server/servlet/ClientExceptionHandler.java contains a string
// constant that needs to match this.
SEVERE,
/** An error but the application has recovered / worked around the issue */
WARNING,
/** For reasonably sparse, high level information */
INFO,
/** Verbose information */
DEBUG
}
/**
* A simple wrapper around the logs interface that curries up a stream name.
*
* Please read details in {@link Logs#log(String, Level, Object...)}
*/
public interface Log {
public void log(Level level, Object... objects);
public static final Log DEV_NULL = new Log() {
@Override public void log(Level level, Object... objects) { }
};
}
/**
* Handler for log entries, to implement functionality such as rendering log
* entries, reporting errors to a server, etc.
*/
public interface Handler {
/**
* Tests if this handler is ready to receive entries. This is called by the
* logger, usually asynchronously after items have been logged.
*
* @return true if the handler wishes to have the new entries pushed to it.
*/
boolean canReceive();
/**
* Called for each log entry to be received by the handler. This will only
* happen when {@link #canReceive()} returns true, or if someone manually
* calls {@link Logs#pushEntries(int,Handler)}.
*
* Do not mutate the objects array as it is shared with other handlers.
*
* NOTE(danilatos): The first UmbrellaException is unwrapped and replaced
* with its first cause in both the objects array and the first throwable.
*
* @param objects the complete set of objects logged
* @param firstThrowable the first instance of a throwable inside objects.
*/
void receiveEntry(int num, double timestamp, String stream, Level level, Object[] objects,
Throwable firstThrowable);
}
/**
* See {@link Entry#firstThrowable}
*/
private static final Throwable NO_THROWABLE_INSTANCE = new Throwable();
private static class Entry {
private double timestamp;
private String stream;
private Level level;
private Object[] objects;
/**
* Null if not initialized, {@link Logs#NO_THROWABLE_INSTANCE} if it is
* initialized and should be regarded as null (no throwable exists in the
* log entry).
*/
private Throwable firstThrowable;
}
private static final int MAX_ENTRIES_BUFFERED = 200;
private static final Logs INSTANCE = new Logs(SchedulerInstance.getMediumPriorityTimer());
public static Logs get() {
return INSTANCE;
}
public static Log create(final String streamName) {
return new Log() {
@Override
public void log(Level level, Object... objects) {
INSTANCE.log(streamName, level, objects);
}
};
}
private final Scheduler.Task notifier = new Scheduler.Task() {
@Override public void execute() {
isScheduled = false;
flush();
}
};
private final TimerService timer;
private final Collection<Handler> handlers = CollectionUtils.createQueue();
/**
* Buffer for entries, so we can batch notifications to handlers.
*/
private final Entry[] entries = new Entry[MAX_ENTRIES_BUFFERED];
/**
* Optimization for notifier
*/
private boolean isScheduled = false;
/**
* Number of unflushed (notification not sent) log entries. Must not exceed
* {@link #MAX_ENTRIES_BUFFERED}.
*/
private int unflushed = 0;
/**
* Index into the {@link #entries} array where the next entry will go.
*/
private int next = 0;
/**
* Total entries ever logged
*/
private int total = 0;
Logs(TimerService timer) {
this.timer = timer;
for (int i = 0; i < entries.length; i++) {
entries[i] = new Entry();
}
}
public void addHandler(Handler h) {
flush();
if (!handlers.contains(h)) {
handlers.add(h);
}
}
/**
* As handling of the log entry may be deferred, objects passed should be
* immutable with respect to their {@link #toString()} method. (This is
* trivially the case for Strings themselves and any other immutable objects).
*
* It is best to comma-separate message components rather than concatenating
* eagerly, to avoid expensive string concatenation and calculation of
* {@link #toString()} methods for large objects, which can be slow, and
* unnecessary if the log entry is to be filtered out according to the current
* settings.
*
* If the result of an object's {@link #toString()} method is expected to
* change after a time, it may be necessary to eagerly convert it to a string
* at the call site to preserve log message correctness (but keeping in mind
* the performance implications).
*
* @param stream application component stream (for horizontal filtering)
* @param level log level (for vertical filtering)
* @param objects
*/
public void log(String stream, Level level, Object... objects) {
// We do not want to lose log entries, so flush synchronously if the
// buffer is full.
if (unflushed == entries.length) {
flush();
}
Entry entry = entries[next];
entry.timestamp = timer.currentTimeMillis();
entry.stream = stream;
entry.level = level;
entry.objects = objects;
next = (next + 1) % entries.length;
unflushed++;
total++;
assert next == total % entries.length;
// isScheduled check is technically redundant as the scheduler will do it...
// but this way is SUPER OPTIMIZED.
if (!isScheduled) {
timer.schedule(notifier);
isScheduled = true;
}
}
public void pushEntries(int from, Handler h) {
for (int i = Math.max(from, total - entries.length); i < total; i++) {
Entry e = entries[i % entries.length];
h.receiveEntry(i, e.timestamp, e.stream, e.level, e.objects,
getThrowable(e));
}
}
private void flush() {
if (unflushed == 0) {
return;
}
int from = total - unflushed;
unflushed = 0;
for (Handler h : handlers) {
try {
if (h.canReceive()) {
pushEntries(from, h);
}
} catch (Throwable t) {
// We don't want to re-log it, or let it reach the uncaught exception
// handler, because that will likely cause an infinite loop!
// TODO(danilatos): Don't Window.alert() in real production, parametrise
// this with some debug mode if statement thing.
Window.alert("Log handler threw " + t);
}
}
}
/**
* Extracts the Throwable from the entry (and caches it).
* Has the side effect of unwrapping the first UmbrellaException.
*/
private Throwable getThrowable(Entry e) {
if (e.firstThrowable == null) {
e.firstThrowable = NO_THROWABLE_INSTANCE;
Object[] objects = e.objects;
for (int i = 0; i < objects.length; i++) {
if (objects[i] instanceof Throwable) {
Throwable t = (Throwable) objects[i];
// Replace annoying umbrella exceptions with the real one
if (t instanceof UmbrellaException && t.getCause() != null) {
t = t.getCause();
objects[i] = t;
}
e.firstThrowable = t;
break;
}
}
}
return e.firstThrowable != NO_THROWABLE_INSTANCE ? e.firstThrowable : null;
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.shared;
import com.google.inject.Inject;
import com.google.walkaround.util.shared.RandomBase64Generator.RandomProvider;
import java.util.Random;
/**
* Implement {@link RandomProvider} using a {@link Random}.
*
* @author ohler@google.com (Christian Ohler)
*/
public class RandomProviderAdapter implements RandomProvider {
private final Random random;
@Inject
public RandomProviderAdapter(Random random) {
this.random = random;
}
@Override public int nextInt(int n) {
return random.nextInt(n);
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.shared;
import com.google.common.annotations.VisibleForTesting;
import com.google.inject.Inject;
/**
* Produces pseudo-random web-safe base-64 strings.
*
* Thread-safe assuming that the {@link RandomProvider} is.
*/
// TODO(ohler): eliminate duplication with
// org.waveprotocol.wave.examples.fedone.util.RandomBase64Generator
public class RandomBase64Generator {
public interface RandomProvider {
/** @returns a pseudorandom non-negative integer smaller than upperBound */
int nextInt(int upperBound);
}
/** The 64 valid web-safe characters. */
@VisibleForTesting static final char[] WEB64_ALPHABET =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
.toCharArray();
private final RandomProvider random;
@Inject
public RandomBase64Generator(RandomProvider random) {
this.random = random;
}
/**
* Returns a string with {@code length} random base-64 characters.
*/
public String next(int length) {
StringBuilder result = new StringBuilder(length);
for (int i = 0; i < length; i++) {
result.append(WEB64_ALPHABET[random.nextInt(64)]);
}
return result.toString();
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.shared;
import com.google.common.base.Preconditions;
import java.util.AbstractList;
import java.util.List;
/**
* An unmodifiable live view of the concatenation of two lists.
*
* The implementation is only efficient if the two lists support efficient
* random access.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class ConcatenatingList<T> extends AbstractList<T> {
public static final <T> ConcatenatingList<T> of(List<T> a, List<T> b) {
return new ConcatenatingList<T>(a, b);
}
private final List<T> a;
private final List<T> b;
public ConcatenatingList(List<T> a, List<T> b) {
this.a = Preconditions.checkNotNull(a, "Null a");
this.b = Preconditions.checkNotNull(b, "Null b");
}
@Override
public T get(int index) {
return index < a.size() ? a.get(index) : b.get(index - a.size());
}
@Override
public int size() {
return a.size() + b.size();
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.shared;
import com.google.common.annotations.VisibleForTesting;
import javax.annotation.Nullable;
/**
* Similar to {@link com.google.common.base.Preconditions} but for assertions.
* We use this instead of {@code assert} because ensuring whether {@code assert}
* is enabled in a given environment can be difficult.
*
* @author ohler@google.com (Christian Ohler)
*/
public class Assert {
private Assert() {}
/**
* Ensures the truth of an expression.
*
* @param expression a boolean expression
* @throws AssertionError if {@code expression} is false
*/
public static void check(boolean expression) {
if (!expression) {
throw new AssertionError();
}
}
/**
* Ensures the truth of an expression.
*
* @param expression a boolean expression
* @param errorMessage the exception message to use if the check fails; will
* be converted to a string using {@link String#valueOf(Object)}
* @throws AssertionError if {@code expression} is false
*/
public static void check(boolean expression, @Nullable Object errorMessage) {
if (!expression) {
throw new AssertionError(String.valueOf(errorMessage));
}
}
/**
* Ensures the truth of an expression.
*
* @param expression a boolean expression
* @param errorMessageTemplate a template for the exception message should the
* check fail. The message is formed by replacing each {@code %s}
* placeholder in the template with an argument. These are matched by
* position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
* Unmatched arguments will be appended to the formatted message in square
* braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}.
* @throws IllegalArgumentException if {@code expression} is false
* @throws NullPointerException if the check fails and either {@code
* errorMessageTemplate} or {@code errorMessageArgs} is null (don't let
* this happen)
*/
public static void check(boolean expression,
@Nullable String errorMessageTemplate,
@Nullable Object... errorMessageArgs) {
if (!expression) {
throw new AssertionError(
format(errorMessageTemplate, errorMessageArgs));
}
}
/**
* Substitutes each {@code %s} in {@code template} with an argument. These
* are matched by position - the first {@code %s} gets {@code args[0]}, etc.
* If there are more arguments than placeholders, the unmatched arguments will
* be appended to the end of the formatted message in square braces.
*
* @param template a non-null string containing 0 or more {@code %s}
* placeholders.
* @param args the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}. Arguments can be null.
*/
@VisibleForTesting static String format(String template,
@Nullable Object... args) {
template = String.valueOf(template); // null -> "null"
// start substituting the arguments into the '%s' placeholders
StringBuilder builder = new StringBuilder(
template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
while (i < args.length) {
int placeholderStart = template.indexOf("%s", templateStart);
if (placeholderStart == -1) {
break;
}
builder.append(template.substring(templateStart, placeholderStart));
builder.append(args[i++]);
templateStart = placeholderStart + 2;
}
builder.append(template.substring(templateStart));
// if we run out of placeholders, append the extra args in square braces
if (i < args.length) {
builder.append(" [");
builder.append(args[i++]);
while (i < args.length) {
builder.append(", ");
builder.append(args[i++]);
}
builder.append(']');
}
return builder.toString();
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.appengine;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.appengine.api.memcache.Expiration;
import com.google.appengine.api.memcache.InvalidValueException;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheService.SetPolicy;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.google.appengine.api.taskqueue.DeferredTask;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.common.base.Objects;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import com.google.walkaround.util.server.RetryHelper.PermanentFailure;
import com.google.walkaround.util.server.RetryHelper.RetryableFailure;
import com.google.walkaround.util.server.appengine.CheckedDatastore.CheckedTransaction;
import java.io.Serializable;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* A wrapper around App Engine's MemcacheService that provides stronger typing
* and prepends a user-defined prefix to all keys to make it easier to avoid
* collisions.
*
* @author ohler@google.com (Christian Ohler)
*
* @param <K> key type
* @param <V> value type
*/
public class MemcacheTable<K extends Serializable, V extends Serializable> {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(MemcacheTable.class.getName());
public interface Factory {
<K extends Serializable, V extends Serializable> MemcacheTable<K, V> create(String tag);
}
// Guice says "Factory cannot be used as a key; It is not fully specified."
// Looks like we can't use FactoryModuleBuilder and have to write our own
// implementation.
public static class FactoryImpl implements Factory {
private final MemcacheService service;
private final Queue deletionQueue;
@Inject
public FactoryImpl(MemcacheService service, @MemcacheDeletionQueue Queue deletionQueue) {
this.service = service;
this.deletionQueue = deletionQueue;
}
@Override public <K extends Serializable, V extends Serializable> MemcacheTable<K, V> create(
String tag) {
return new MemcacheTable<K, V>(service, deletionQueue, tag);
}
}
private static class TaggedKey<K extends Serializable> implements Serializable {
private static final long serialVersionUID = 267550222157163337L;
private final String tag;
@Nullable private final K key;
public TaggedKey(String tag, @Nullable K key) {
this.tag = checkNotNull(tag, "Null tag");
this.key = key;
}
public String getTag() {
return tag;
}
@Nullable public K getKey() {
return key;
}
@Override public String toString() {
return "TaggedKey(" + tag + ", " + key + ")";
}
@Override public final boolean equals(Object o) {
if (o == this) { return true; }
if (!(o instanceof TaggedKey)) { return false; }
TaggedKey<?> other = (TaggedKey<?>) o;
return Objects.equal(tag, other.tag)
&& Objects.equal(key, other.key);
}
@Override public final int hashCode() {
return Objects.hashCode(tag, key);
}
}
public static class IdentifiableValue<V> {
private final MemcacheService.IdentifiableValue inner;
IdentifiableValue(MemcacheService.IdentifiableValue inner) {
this.inner = checkNotNull(inner, "Null inner");
}
@Override public String toString() {
return getClass().getSimpleName() + "(" + inner.getValue() + ")";
}
@SuppressWarnings("unchecked")
public V getValue() {
return (V) inner.getValue();
}
}
private final MemcacheService service;
private final String tag;
private final Queue deletionQueue;
/**
* @param tag a unique tag that distinguishes this table from other tables.
* Since memcache persists through application reloads, you have to explicitly
* clear the cache first if you ever want to re-use a tag for different data.
*/
@Inject
public MemcacheTable(MemcacheService service, @MemcacheDeletionQueue Queue deletionQueue,
@Assisted String tag) {
this.service = service;
this.deletionQueue = deletionQueue;
this.tag = tag;
}
private static class PutNullTask implements DeferredTask {
private static final long serialVersionUID = 483212086178559149L;
private final TaggedKey<?> key;
PutNullTask(TaggedKey<?> key) {
this.key = checkNotNull(key, "Null key");
}
@Override public void run() {
log.info("Deferred overwrite for memcache key " + key);
// We have to put null rather than deleting since what we do here must
// interfere with a concurrent getIdentifiable/putIfUntouched sequence,
// and MemcacheService's Javadoc does not specify that putIfUntouched will
// abort if the value was absent during the lookup and delete has been
// called between the lookup and putIfUntouched.
MemcacheServiceFactory.getMemcacheService().put(key, null);
}
}
public void enqueuePutNull(CheckedTransaction tx, @Nullable K key)
throws RetryableFailure, PermanentFailure {
tx.enqueueTask(deletionQueue, TaskOptions.Builder.withPayload(new PutNullTask(tagKey(key))));
}
// Cast is safe under the assumption that tag is not re-used for a different
// type
@SuppressWarnings("unchecked")
@Nullable private V castRawValue(Object rawValue) {
return (V) rawValue;
}
private TaggedKey<K> tagKey(@Nullable K key) {
return new TaggedKey<K>(tag, key);
}
public void delete(@Nullable K key) {
TaggedKey<K> taggedKey = tagKey(key);
log.info("cache delete " + taggedKey);
service.delete(taggedKey);
}
public void put(@Nullable K key, @Nullable V value) {
put(key, value, null);
}
public void put(@Nullable K key, @Nullable V value, @Nullable Expiration expires) {
put(key, value, expires, SetPolicy.SET_ALWAYS);
}
/**
* @return true if a new entry was created, false if not because of the
* policy.
*/
public boolean put(@Nullable K key, @Nullable V value, @Nullable Expiration expires,
SetPolicy policy) {
TaggedKey<K> taggedKey = tagKey(key);
String expiresString = expires == null ? null : "" + expires.getMillisecondsValue();
log.info("cache put " + taggedKey + " = " + value + ", " + expiresString + ", " + policy);
return service.put(taggedKey, value, expires, policy);
}
/**
* @return the set of keys for which new entries were created (some may not
* have been created because of the policy).
*/
public Set<K> putAll(Map<K, V> mappings, @Nullable Expiration expires, SetPolicy policy) {
Map<TaggedKey<K>, V> rawMappings = Maps.newHashMapWithExpectedSize(mappings.size());
for (Map.Entry<K, V> entry : mappings.entrySet()) {
rawMappings.put(tagKey(entry.getKey()), entry.getValue());
}
Set<TaggedKey<K>> rawResult = service.putAll(rawMappings, expires, policy);
Set<K> result = Sets.newHashSetWithExpectedSize(rawResult.size());
for (TaggedKey<K> key : rawResult) {
result.add(key.getKey());
}
return result;
}
@Nullable public V get(@Nullable K key) {
TaggedKey<K> taggedKey = tagKey(key);
Object rawValue;
try {
rawValue = service.get(taggedKey);
} catch (InvalidValueException e) {
// Probably a deserialization error (incompatible serialVersionUID or similar).
log.log(Level.WARNING, "Error getting object from memcache, key: " + key, e);
return null;
}
if (rawValue == null) {
log.info("cache miss " + taggedKey);
return null;
} else {
log.info("cache hit " + taggedKey + " = " + rawValue);
// TODO(ohler): check actual type
return castRawValue(rawValue);
}
}
public Map<K, V> getAll(Set<K> keys) {
Set<TaggedKey<K>> taggedKeys = Sets.newHashSetWithExpectedSize(keys.size());
for (K key : keys) {
taggedKeys.add(tagKey(key));
}
Map<TaggedKey<K>, Object> rawMappings;
try {
rawMappings = service.getAll(taggedKeys);
} catch (InvalidValueException e) {
// Probably a deserialization error (incompatible serialVersionUID or similar).
log.log(Level.WARNING, "Error getting objects from memcache, keys: " + keys, e);
return Collections.emptyMap();
}
Map<K, V> mappings = Maps.newHashMapWithExpectedSize(rawMappings.size());
for (Map.Entry<TaggedKey<K>, Object> entry : rawMappings.entrySet()) {
mappings.put(entry.getKey().getKey(), castRawValue(entry.getValue()));
}
log.info("Found " + mappings.size() + " of " + keys.size() + " objects in memcache: "
+ mappings);
return mappings;
}
@Nullable public IdentifiableValue<V> getIdentifiable(@Nullable K key) {
TaggedKey<K> taggedKey = tagKey(key);
MemcacheService.IdentifiableValue rawValue;
try {
rawValue = service.getIdentifiable(taggedKey);
} catch (InvalidValueException e) {
// Probably a deserialization error (incompatible serialVersionUID or similar).
log.log(Level.WARNING, "Error getting object from memcache, key: " + key, e);
return null;
}
if (rawValue == null) {
log.info("cache miss " + taggedKey);
return null;
} else {
log.info("cache hit " + taggedKey + " = " + rawValue);
return new IdentifiableValue<V>(rawValue);
}
}
/**
* NOTE: This differs from {@link MemcacheService} in that it allows oldValue
* to be null, in which case it will put unconditionally.
*/
public boolean putIfUntouched(@Nullable K key, IdentifiableValue<V> oldValue,
@Nullable V newValue) {
return putIfUntouched(key, oldValue, newValue, null);
}
/**
* NOTE: This differs from {@link MemcacheService} in that it allows oldValue
* to be null, in which case it will put unconditionally.
*/
public boolean putIfUntouched(@Nullable K key, IdentifiableValue<V> oldValue,
@Nullable V newValue, @Nullable Expiration expires) {
TaggedKey<K> taggedKey = tagKey(key);
String expiresString = expires == null ? null : "" + expires.getMillisecondsValue();
boolean result;
if (oldValue == null) {
service.put(taggedKey, newValue, expires);
result = true;
} else {
result = service.putIfUntouched(taggedKey, oldValue.inner, newValue, expires);
}
log.info("cache putIfUntouched " + taggedKey + " = " + newValue
+ ", " + expiresString + ": " + result);
return result;
}
// TODO(ohler): Add more methods here to match MemcacheService.
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.appengine;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Guice annotation for the GAE task queue used for deleting memcache entries
* after datastore transactions.
*
* @author ohler@google.com (Christian Ohler)
*/
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface MemcacheDeletionQueue {}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.appengine;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.tools.mapreduce.AppEngineMapper;
import org.apache.hadoop.io.NullWritable;
import java.util.logging.Logger;
/**
* @author ohler@google.com (Christian Ohler)
*/
public class DeleteAllMapper extends AppEngineMapper<Key, Entity, NullWritable, NullWritable> {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(DeleteAllMapper.class.getName());
// (loop repeat 20 do (insert (+ ?a (random 26))))
private static final String CONFIRMATION_COOKIE = "DELETE_imakzeojnacjfsvbrxhu";
@Override
public void map(Key key, Entity value, Context context) {
boolean really = CONFIRMATION_COOKIE.equals(
context.getConfiguration().get("zz_confirmationCookie"));
context.getCounter(getClass().getSimpleName(), "entities-seen").increment(1);
if (really) {
log.info("really deleting: " + key + ", " + value);
getAppEngineContext(context).getMutationPool().delete(key);
context.getCounter(getClass().getSimpleName(), "entities-really-deleted").increment(1);
} else {
log.info("not really deleting: " + key + ", " + value);
context.getCounter(getClass().getSimpleName(), "entities-not-really-deleted").increment(1);
}
context.getCounter(getClass().getSimpleName(), "entities-processed").increment(1);
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.appengine;
import com.google.appengine.api.datastore.Entity;
import com.google.common.base.Preconditions;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* @author ohler@google.com (Christian Ohler)
*/
public class DatastoreUtil {
/**
* Thrown by methods that parse entities if properties are invalid or missing.
*/
public static class InvalidPropertyException extends RuntimeException {
private static final long serialVersionUID = 211006788308217422L;
public InvalidPropertyException(Entity entity, String propertyName) {
this(entity, propertyName, null, null);
}
public InvalidPropertyException(Entity entity, String propertyName, String message) {
this(entity, propertyName, message, null);
}
public InvalidPropertyException(Entity entity, String propertyName, Throwable cause) {
this(entity, propertyName, null, cause);
}
public InvalidPropertyException(Entity entity, String propertyName,
String message, Throwable cause) {
super(message == null
? ("Invalid property " + propertyName + " in entity " + entity)
: ("Invalid property " + propertyName + " in entity " + entity + ": " + message),
cause);
}
}
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(DatastoreUtil.class.getName());
@Nullable public static <T> T getOptionalProperty(
Entity e, String propertyName, Class<T> propertyType)
throws InvalidPropertyException {
Preconditions.checkNotNull(e, "Null entity");
Preconditions.checkNotNull(propertyName, "Null propertyName");
Preconditions.checkNotNull(propertyType, "Null propertyType");
Object value = e.getProperty(propertyName);
if (value == null) {
return null;
}
if (!propertyType.isInstance(value)) {
throw new InvalidPropertyException(e, propertyName, "Expected property type "
+ propertyType + ", found " + value.getClass() + ": " + value);
}
return propertyType.cast(value);
}
public static <T> T getExistingProperty(Entity e, String propertyName, Class<T> propertyType)
throws InvalidPropertyException {
T value = getOptionalProperty(e, propertyName, propertyType);
if (value == null) {
throw new InvalidPropertyException(e, propertyName, "Property is required but null");
}
return value;
}
/** For Blob and Text, this doesn't really make the property indexed.
* TODO(ohler): disallow Blob and Text? */
public static void setNonNullIndexedProperty(Entity e, String propertyName, Object value) {
Preconditions.checkNotNull(e, "Null entity");
Preconditions.checkNotNull(propertyName, "Null propertyName");
Preconditions.checkNotNull(value, "Null value");
e.setProperty(propertyName, value);
}
public static void setNonNullUnindexedProperty(Entity e, String propertyName, Object value) {
Preconditions.checkNotNull(e, "Null entity");
Preconditions.checkNotNull(propertyName, "Null propertyName");
Preconditions.checkNotNull(value, "Null value");
e.setUnindexedProperty(propertyName, value);
}
/** For Blob and Text, this doesn't really make the property indexed.
* TODO(ohler): disallow Blob and Text? */
public static void setOrRemoveIndexedProperty(
Entity e, String propertyName, @Nullable Object value) {
Preconditions.checkNotNull(e, "Null entity");
Preconditions.checkNotNull(propertyName, "Null propertyName");
if (value == null) {
e.removeProperty(propertyName);
} else {
e.setProperty(propertyName, value);
}
}
public static void setOrRemoveUnindexedProperty(
Entity e, String propertyName, @Nullable Object value) {
Preconditions.checkNotNull(e, "Null entity");
Preconditions.checkNotNull(propertyName, "Null propertyName");
if (value == null) {
e.removeProperty(propertyName);
} else {
e.setUnindexedProperty(propertyName, value);
}
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.appengine;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.walkaround.util.server.RetryHelper;
import com.google.walkaround.util.server.RetryHelper.PermanentFailure;
import com.google.walkaround.util.server.RetryHelper.RetryableFailure;
import com.google.walkaround.util.server.appengine.CheckedDatastore.CheckedTransaction;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* A directory in the datastore that stores a set of T, where each T contains an
* id of type I. Each entity is its own entity group.
*
* @author ohler@google.com (Christian Ohler)
*
* @param <T> entry type
* @param <I> id type
*/
public abstract class AbstractDirectory<T, I> {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(AbstractDirectory.class.getName());
private final CheckedDatastore datastore;
private final String entityKind;
public AbstractDirectory(CheckedDatastore datastore, String entityKind) {
Preconditions.checkNotNull(datastore, "Null datastore");
Preconditions.checkNotNull(entityKind, "Null entityKind");
this.datastore = datastore;
this.entityKind = entityKind;
}
protected abstract String serializeId(I id);
protected abstract I getId(T e);
protected abstract void populateEntity(T in, Entity out);
protected abstract T parse(Entity e);
@VisibleForTesting
public Key makeKey(I id) {
return KeyFactory.createKey(entityKind, serializeId(id));
}
@Nullable public T get(CheckedTransaction tx, I id) throws PermanentFailure, RetryableFailure {
Key key = makeKey(id);
Entity result = tx.get(key);
if (result != null) {
log.info("Looked up " + key + ", found " + result);
return parse(result);
} else {
log.info("Looked up " + key + ", not found");
return null;
}
}
@Nullable public T getWithoutTx(I id) throws IOException {
try {
CheckedTransaction tx = datastore.beginTransaction();
try {
return get(tx, id);
} finally {
tx.rollback();
}
} catch (PermanentFailure e) {
log.log(Level.SEVERE, "Failed to look up " + id, e);
throw new IOException(e);
} catch (RetryableFailure e) {
log.log(Level.SEVERE, "Failed to look up " + id, e);
throw new IOException(e);
}
}
public void put(CheckedTransaction tx, T newEntry) throws PermanentFailure, RetryableFailure {
Preconditions.checkNotNull(tx, "Null tx");
Preconditions.checkNotNull(newEntry, "Null newEntry");
Key key = makeKey(getId(newEntry));
Entity newEntity = new Entity(key);
populateEntity(newEntry, newEntity);
// For now, we verify that it parses with no exceptions. We can turn
// this off if it's too expensive.
parse(newEntity);
log.info("Putting " + newEntity + " in " + tx);
tx.put(newEntity);
}
public void putWithoutTx(final T newEntry) throws IOException {
Preconditions.checkNotNull(newEntry, "Null newEntry");
try {
new RetryHelper().run(new RetryHelper.VoidBody() {
@Override public void run() throws RetryableFailure, PermanentFailure {
CheckedTransaction tx = datastore.beginTransaction();
try {
put(tx, newEntry);
tx.commit();
log.info("Committed " + tx);
} finally {
tx.close();
}
}
});
} catch (PermanentFailure e) {
throw new IOException(e);
}
}
/**
* Transactionally checks if an entry with the same key as newEntry exists,
* and adds newEntry if not. If an entry already exists, returns the existing
* entry; otherwise (i.e., if newEntry was added), returns null.
*/
// NOTE(danilatos): Don't be tempted to implement a version of this method that
// accepts a Provider or something in order to only create the newEntry if one
// does not exist in the datastore, because megastore transactions run in parallel
// and just fail on commit (there is no locking).
// Instead, use get() and then getOrAdd() if get returns null.
// Is this method worthwhile, given that a caller can just use get() and put()
// and manage their own transaction?
@Nullable public T getOrAdd(final T newEntry) throws IOException {
Preconditions.checkNotNull(newEntry, "Null newEntry");
try {
return new RetryHelper().run(new RetryHelper.Body<T>() {
@Override public T run() throws RetryableFailure, PermanentFailure {
CheckedTransaction tx = datastore.beginTransaction();
try {
Entity existing = tx.get(makeKey(getId(newEntry)));
if (existing != null) {
log.info("Read " + existing + " in " + tx);
return parse(existing);
} else {
put(tx, newEntry);
tx.commit();
log.info("Committed " + tx);
return null;
}
} finally {
tx.close();
}
}
});
} catch (PermanentFailure e) {
throw new IOException(e);
}
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.appengine;
import com.google.appengine.api.datastore.CommittedButStillApplyingException;
import com.google.appengine.api.datastore.Cursor;
import com.google.appengine.api.datastore.DatastoreFailureException;
import com.google.appengine.api.datastore.DatastoreNeedIndexException;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreTimeoutException;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.QueryResultIterator;
import com.google.appengine.api.datastore.Transaction;
import com.google.appengine.api.datastore.TransactionOptions;
import com.google.appengine.api.taskqueue.InternalFailureException;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.TaskHandle;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TransientFailureException;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import com.google.walkaround.util.server.RetryHelper.PermanentFailure;
import com.google.walkaround.util.server.RetryHelper.RetryableFailure;
import java.util.ConcurrentModificationException;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A wrapper around {@link DatastoreService} that throws checked exceptions
* for failures.
*
* @author danilatos@google.com (Daniel Danilatos)
* @author ohler@google.com (Christian Ohler)
*/
// TODO(ohler): Eliminate PermanentFailure and RetryableFailure from this
// interface. The exception types that we throw should express what happened;
// how to deal with it (whether to retry or not) is the up to the caller to
// decide. PermanentFailure and RetryableFailure were only intended to be
// RetryHelper's API, not to be used everywhere. (Maybe it is not a good API.
// An alternative API would be to signal the need for a retry in a similar way
// to Guava's AbstractIterator.endOfData(), and to use RuntimeExceptions to
// abort the body with a permanent failure.)
public class CheckedDatastore {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(CheckedDatastore.class.getName());
private interface Evaluater<T> {
T run() throws RetryableFailure, PermanentFailure;
}
public interface CheckedIterator {
boolean hasNext() throws PermanentFailure, RetryableFailure;
Entity next() throws PermanentFailure, RetryableFailure;
Cursor getCursor() throws PermanentFailure, RetryableFailure;
public static final CheckedIterator EMPTY = new CheckedIterator() {
@Override public boolean hasNext() {
return false;
}
@Override public Entity next() {
throw new NoSuchElementException("empty iterator");
}
@Override public Cursor getCursor() {
throw new UnsupportedOperationException("Not implemented");
}
};
}
/**
* A wrapper around {@link QueryResultIterator}<{@link Entity}> that throws
* checked exceptions for failures.
*/
private static class CheckedIteratorImpl implements CheckedIterator {
private final QueryResultIterator<Entity> iterator;
CheckedIteratorImpl(QueryResultIterator<Entity> iterator) {
Preconditions.checkNotNull(iterator, "Null iterator");
this.iterator = iterator;
}
@Override public boolean hasNext() throws PermanentFailure, RetryableFailure {
return safeRun(new Evaluater<Boolean>() {
@Override public Boolean run() {
return iterator.hasNext();
}
});
}
@Override public Entity next() throws PermanentFailure, RetryableFailure {
return safeRun(new Evaluater<Entity>() {
@Override public Entity run() {
return iterator.next();
}
});
}
@Override public Cursor getCursor() throws PermanentFailure, RetryableFailure {
return safeRun(new Evaluater<Cursor>() {
@Override public Cursor run() {
return iterator.getCursor();
}
});
}
@Override public String toString() {
return "CheckedIteratorImpl(" + iterator + ")";
}
}
/**
* A wrapper around {@link PreparedQuery} that throws checked exceptions for
* failures.
*/
public abstract static class CheckedPreparedQuery {
public abstract CheckedIterator asIterator(final FetchOptions options)
throws PermanentFailure, RetryableFailure;
public CheckedIterator asIterator() throws PermanentFailure, RetryableFailure {
return asIterator(FetchOptions.Builder.withDefaults());
}
public abstract List<Entity> asList(final FetchOptions options)
throws PermanentFailure, RetryableFailure;
public List<Entity> asList() throws PermanentFailure, RetryableFailure {
return asList(FetchOptions.Builder.withDefaults());
}
public abstract int countEntities(final FetchOptions options)
throws PermanentFailure, RetryableFailure;
public Entity asSingleEntity() throws PermanentFailure, RetryableFailure {
// We could say withLimit(2) here, but that's only more efficient in the
// failure case, and in that case, the improved diagnostics are probably
// worth the cost.
List<Entity> results = asList(FetchOptions.Builder.withLimit(10));
switch (results.size()) {
case 0:
return null;
case 1:
return results.get(0);
default:
throw new RuntimeException("Found more than one result for " + this
+ "; some of them are: " + results + " (not exhaustive)");
}
}
public Entity getFirstResult() throws PermanentFailure, RetryableFailure {
List<Entity> results = asList(FetchOptions.Builder.withLimit(1));
return results.isEmpty() ? null : results.get(0);
}
}
/**
* A wrapper around {@link PreparedQuery} that throws checked exceptions for
* failures.
*/
private static class CheckedPreparedQueryImpl extends CheckedPreparedQuery {
private final PreparedQuery q;
private CheckedPreparedQueryImpl(PreparedQuery q) {
Preconditions.checkNotNull(q, "Null q");
this.q = q;
}
@Override public String toString() {
return "CheckedPreparedQueryImpl(" + q + ")";
}
@Override public CheckedIterator asIterator(final FetchOptions options)
throws PermanentFailure, RetryableFailure {
return safeRun(new Evaluater<CheckedIterator>() {
@Override public CheckedIterator run() {
return new CheckedIteratorImpl(q.asQueryResultIterator(options));
}
});
}
@Override public List<Entity> asList(final FetchOptions options)
throws PermanentFailure, RetryableFailure {
return safeRun(new Evaluater<List<Entity>>() {
@Override public List<Entity> run() {
return q.asList(options);
}
});
}
@Override public int countEntities(final FetchOptions options)
throws PermanentFailure, RetryableFailure {
return safeRun(new Evaluater<Integer>() {
@Override public Integer run() {
return q.countEntities(options);
}
});
}
}
public interface CheckedTransaction {
// Read access.
Entity get(Key key) throws PermanentFailure, RetryableFailure;
Map<Key, Entity> get(Iterable<Key> keys) throws PermanentFailure, RetryableFailure;
CheckedPreparedQuery prepare(Query q);
// Write access.
Key put(Entity e) throws PermanentFailure, RetryableFailure;
List<Key> put(Iterable<Entity> e) throws PermanentFailure, RetryableFailure;
void delete(Key... keys) throws PermanentFailure, RetryableFailure;
TaskHandle enqueueTask(Queue queue, TaskOptions task) throws PermanentFailure, RetryableFailure;
// Transaction lifecycle management.
void rollback();
void commit() throws PermanentFailure, RetryableFailure;
boolean isActive();
/** Shorthand for {@code if (isActive()) rollback();}. */
void close();
void runAfterCommit(Runnable r);
}
private class CheckedTransactionImpl implements CheckedTransaction {
private final Transaction transaction;
private final List<Runnable> postCommitRunnables = Lists.newArrayList();
CheckedTransactionImpl(Transaction transaction) {
this.transaction = transaction;
}
@Override
public String toString() {
return "CheckedTransactionImpl(" + transaction
+ String.format(" (%s@%x)", transaction.getClass(), System.identityHashCode(transaction))
+ ")";
}
@Override
public Entity get(final Key key) throws PermanentFailure, RetryableFailure {
return safeRun(new Evaluater<Entity>() {
@Override public Entity run() {
try {
return datastore.get(transaction, key);
} catch (EntityNotFoundException e) {
return null;
}
}
});
}
@Override
public Map<Key, Entity> get(final Iterable<Key> keys)
throws PermanentFailure, RetryableFailure {
return safeRun(new Evaluater<Map<Key, Entity>>() {
@Override public Map<Key, Entity> run() {
return datastore.get(transaction, keys);
}
});
}
@Override
public CheckedPreparedQuery prepare(Query q) {
// TODO(ohler): confirm that this doesn't need safeRun, and document why not
return new CheckedPreparedQueryImpl(datastore.prepare(transaction, q));
}
@Override
public Key put(final Entity e) throws PermanentFailure, RetryableFailure {
return safeRun(new Evaluater<Key>() {
@Override public Key run() {
return datastore.put(transaction, e);
}
});
}
@Override
public List<Key> put(final Iterable<Entity> e) throws PermanentFailure, RetryableFailure {
return safeRun(new Evaluater<List<Key>>() {
@Override public List<Key> run() {
return datastore.put(transaction, e);
}
});
}
@Override
public void delete(final Key... keys) throws PermanentFailure, RetryableFailure {
safeRun(new Evaluater<Void>() {
@Override public Void run() {
datastore.delete(transaction, keys);
return null;
}
});
}
@Override
public TaskHandle enqueueTask(final Queue queue, final TaskOptions task)
throws PermanentFailure, RetryableFailure {
return safeRun(new Evaluater<TaskHandle>() {
@Override public TaskHandle run() throws RetryableFailure, PermanentFailure {
try {
return queue.add(transaction, task);
} catch (InternalFailureException e) {
// Perhaps the fact that this is different from
// TransientFailureException suggests that we shouldn't retry, but
// neither the exception type nor the documentation are explicit
// about it, so let's retry.
throw new RetryableFailure("Internal task queue failure enqueueing " + task, e);
} catch (TransientFailureException e) {
throw new RetryableFailure("Transient task queue failure enqueueing " + task, e);
}
}
});
}
@Override
public void rollback() {
try {
safeRun(new Evaluater<Void>() {
@Override public Void run() {
transaction.rollback();
return null;
}
});
} catch (PermanentFailure e) {
log.log(Level.SEVERE, "Exception during rollback, ignoring", e);
} catch (RetryableFailure e) {
log.log(Level.WARNING, "Exception during rollback, ignoring", e);
} catch (IllegalArgumentException e) {
// Datastore gives us IllegalArgumentException when the transaction has timed out.
log.log(Level.WARNING, "IllegalArgumentException during rollback, ignoring", e);
}
}
@Override
public void commit() throws PermanentFailure, RetryableFailure {
safeRun(new Evaluater<Void>() {
@Override public Void run() {
try {
transaction.commit();
} catch (CommittedButStillApplyingException e) {
// just log warning for now out of curiosity.
// we could just totally ignore it.
log.log(Level.WARNING, "still applying", e);
}
return null;
}
});
for (Runnable r : postCommitRunnables) {
r.run();
}
}
@Override
public boolean isActive() {
return transaction.isActive();
}
@Override
public void close() {
if (isActive()) {
rollback();
}
}
@Override
public void runAfterCommit(Runnable r) {
postCommitRunnables.add(r);
}
}
private final DatastoreService datastore;
@Inject
public CheckedDatastore(DatastoreService datastore) {
this.datastore = datastore;
}
private CheckedTransaction beginTransaction(final TransactionOptions options)
throws PermanentFailure, RetryableFailure {
return safeRun(new Evaluater<CheckedTransaction>() {
@Override public CheckedTransaction run() {
Transaction rawTransaction = datastore.beginTransaction(options);
// NOTE(ohler): Calling rawTransaction.getId() forces TransactionImpl to
// wait for the result of the beginTransaction RPC. We do this here to
// get the DatastoreTimeoutException (in the case of a timeout) right
// away rather than at some surprising time later in
// TransactionImpl.toString() or similar.
//
// Hopefully, TransactionImpl will be fixed to eliminate the need for
// this.
try {
rawTransaction.getId();
} catch (DatastoreTimeoutException e) {
// We don't log transaction itself because I'm worried its toString()
// might fail. TODO(ohler): confirm this.
log.log(Level.WARNING, "Failed to begin transaction", e);
// Now we need to roll back the transaction (even though it doesn't
// actually exist), otherwise TransactionCleanupFilter will try to
// roll it back, which is bad because it's not prepared for the crash
// that we catch below.
try {
rawTransaction.rollback();
throw new Error("Rollback of nonexistent transaction did not fail");
} catch (DatastoreTimeoutException e2) {
log.log(Level.INFO, "Rollback of nonexistent transaction failed as expected", e2);
}
throw e;
}
CheckedTransaction checkedTransaction = new CheckedTransactionImpl(rawTransaction);
log.info("Begun transaction " + checkedTransaction);
return checkedTransaction;
}
});
}
public CheckedTransaction beginTransactionXG() throws PermanentFailure, RetryableFailure {
return beginTransaction(TransactionOptions.Builder.withXG(true));
}
public CheckedTransaction beginTransaction() throws PermanentFailure, RetryableFailure {
return beginTransaction(TransactionOptions.Builder.withDefaults());
}
public CheckedPreparedQuery prepareNontransactionalQuery(Query q) {
// TODO(ohler): confirm that this doesn't need safeRun, and document why not
return new CheckedPreparedQueryImpl(datastore.prepare(q));
}
public DatastoreService unsafe() {
return datastore;
}
private static <T> T safeRun(Evaluater<T> runnable) throws PermanentFailure, RetryableFailure {
try {
return runnable.run();
} catch (DatastoreTimeoutException e) {
throw new RetryableFailure(e);
} catch (ConcurrentModificationException e) {
throw new RetryableFailure(e);
} catch (DatastoreFailureException e) {
throw new PermanentFailure(e);
} catch (DatastoreNeedIndexException e) {
throw new PermanentFailure(e);
} catch (PreparedQuery.TooManyResultsException e) {
throw new PermanentFailure(e);
}
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.flags;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Binder;
import com.google.inject.Provider;
import com.google.inject.binder.LinkedBindingBuilder;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
import java.util.Map;
/**
* Parses flags from a JSON map.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class JsonFlags {
private JsonFlags() {}
private static <T extends Enum<T>> T parseEnumValue(Class<T> enumType, String key, String value)
throws FlagFormatException {
try {
return Enum.valueOf(enumType, value);
} catch (IllegalArgumentException e) {
throw new FlagFormatException("Invalid flag enum value " + value + " for key " + key
+ "; valid values: " + Arrays.toString(enumType.getEnumConstants()), e);
}
}
@VisibleForTesting
@SuppressWarnings("unchecked")
static Object parseOneFlag(FlagDeclaration decl, JSONObject json) throws FlagFormatException {
String key = decl.getName();
Class<?> type = decl.getType();
try {
if (!json.has(key)) {
throw new FlagFormatException("Missing flag: " + key);
}
// Explicit check, otherwise null would be interpreted as "null" (the
// string) for string and enum values.
if (json.isNull(key)) {
throw new FlagFormatException("Null value for key " + key);
}
if (type == String.class) {
return json.getString(key);
} else if (type == Boolean.class) {
return Boolean.valueOf(json.getBoolean(key));
} else if (type == Integer.class) {
int val = json.getInt(key);
if (val != json.getDouble(key)) {
throw new FlagFormatException("Loss of precision for type int, key=" + key +
", value=" + json.getDouble(key));
}
return Integer.valueOf(val);
} else if (type == Double.class) {
return Double.valueOf(json.getDouble(key));
} else if (type.isEnum()) {
// TODO(ohler): Avoid unchecked warning here, the rest of the method should be clean.
return parseEnumValue(type.asSubclass(Enum.class), key, json.getString(key).toUpperCase());
} else {
throw new IllegalArgumentException("Unknown flag type " + type.getName());
}
} catch (JSONException e) {
throw new FlagFormatException("Invalid flag JSON for key " + key +
" (possibly a bad type); map=" + json, e);
}
}
/**
* The returned map is guaranteed to map every FlagDeclaration
* <code>decl</code> in <code>flagDeclarations</code> to a non-null Object of
* type <code>decl.getType()</code>.
*/
public static Map<FlagDeclaration, Object> parse(
Iterable<? extends FlagDeclaration> flagDeclarations, String jsonString)
throws FlagFormatException {
JSONObject json;
try {
json = new JSONObject(jsonString);
} catch (JSONException e) {
throw new FlagFormatException("Failed to parse jsonString: " + jsonString, e);
}
// TODO(ohler): Detect unknown flags and error (or at least warn).
ImmutableMap.Builder<FlagDeclaration, Object> b = ImmutableMap.builder();
for (FlagDeclaration decl : flagDeclarations) {
b.put(decl, parseOneFlag(decl, json));
}
return b.build();
}
// This assumes that the provider will provide an object of the type required by decl.
@SuppressWarnings("unchecked")
private static void bindOneFlag(Binder binder, FlagDeclaration decl, Provider<Object> provider) {
((LinkedBindingBuilder<Object>) binder.bind(decl.getType()).annotatedWith(decl.getAnnotation()))
.toProvider(provider);
}
/**
* Sets up bindings for the given FlagDeclarations that retrieve the flag
* values from the given configuration provider.
*/
// TODO(ohler): move this out of JsonFlags, it's not specific to JSON.
public static void bind(Binder binder, Iterable<? extends FlagDeclaration> decls,
final Provider<Map<FlagDeclaration, Object>> configProvider) {
for (final FlagDeclaration decl : decls) {
bindOneFlag(binder, decl, new Provider<Object>() {
@Override public Object get() {
return configProvider.get().get(decl);
}
});
}
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.flags;
import java.lang.annotation.Annotation;
/**
* @author ohler@google.com (Christian Ohler)
*/
public interface FlagDeclaration {
/**
* The annotation that is used to mark values that should be injected with the
* value of this flag.
*/
Annotation getAnnotation();
/**
* The name of this flag in the JSON map.
*/
String getName();
Class<?> getType();
// We could add things like isRequired() or getDefaultValue() here; but for
// now, we make all flags required.
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.flags;
/**
* @author danilatos@google.com (Daniel Danilatos)
*/
public class FlagFormatException extends Exception {
private static final long serialVersionUID = 324142638512478969L;
public FlagFormatException() {
}
public FlagFormatException(String message) {
super(message);
}
public FlagFormatException(Throwable cause) {
super(cause);
}
public FlagFormatException(String message, Throwable cause) {
super(message, cause);
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Miscellaneous utilities
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public final class Util {
private Util(){}
/**
* Slurps the contents of a file and returns them as a string.
*
* IOExceptions are re-thrown as RuntimeExceptions.
*/
public static String slurpRequired(String file) {
try {
return slurp(new FileReader(file));
} catch (IOException e) {
throw new RuntimeException("Could not slurp file: " + file
+ " (user.dir=" + System.getProperty("user.dir") + ")", e);
}
}
public static String slurp(Reader in) throws IOException {
BufferedReader reader = new BufferedReader(in);
String line = null;
StringBuilder b = new StringBuilder();
while ((line = reader.readLine()) != null) {
b.append(line);
b.append("\n");
}
return b.toString();
}
public static String slurpUtf8(InputStream stream) throws IOException {
return slurp(new InputStreamReader(stream, "UTF-8"));
}
public static String chomp(String str) {
return (str.charAt(str.length() - 1) == '\n') ? str.substring(0, str.length() - 1) : str;
}
/**
* Returns the first {@code size} characters of the given string.
*/
public static String abbrev(String longString, int size) {
return longString.length() <= size ? longString
: longString.substring(0, size);
}
public static String pathCat(String base, String suffix) {
if (!base.endsWith("/") && !suffix.isEmpty()) {
base += "/";
}
return base + suffix;
}
public static URL makeUrl(String base, String suffix) {
try {
return new URL(pathCat(base, suffix));
} catch (MalformedURLException e) {
throw new RuntimeException("Internal error", e);
}
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.gwt;
import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Adapted from {@link com.google.gwt.logging.server.StackTraceDeobfuscator}
* with some changes.
*
* @author danilatos@google.com (Daniel Danilatos)
* @author ohler@google.com (Christian Ohler)
*/
@Singleton
public class StackTraceDeobfuscator {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(StackTraceDeobfuscator.class.getName());
/** Retrieves symbol maps. */
public interface SymbolMapsDirectory {
InputStream getSymbolMapInputStream(String permutationStrongName) throws IOException;
}
// From JsniRef class, which is in gwt-dev and so can't be accessed here
// TODO: once there is a place for shared code, move this to there.
private static final Pattern JSNI_REF_PATTERN =
Pattern.compile("@?([^:]+)::([^(]+)(\\((.*)\\))?");
private SymbolMapsDirectory symbolMapsDirectory;
// See commit ebb4736368b6d371a1bf5005541d96b88dcac504 for my failed attempt
// at using CacheBuilder. TODO(ohler): Figure out the right solution to this.
@SuppressWarnings("deprecation")
private final Map<String, Map<String, String>> symbolMaps =
new MapMaker()
.maximumSize(100)
.makeComputingMap(
new Function<String, Map<String, String>>() {
@Override public Map<String, String> apply(String strongName) {
try {
// Can't use ImmutableMap.Builder since we may have duplicate keys like $clinit.
Map<String, String> out = new HashMap<String, String>();
BufferedReader bin = new BufferedReader(
new InputStreamReader(
symbolMapsDirectory.getSymbolMapInputStream(strongName)));
try {
String line;
while ((line = bin.readLine()) != null) {
if (line.charAt(0) == '#') {
continue;
}
int idx = line.indexOf(',');
out.put(line.substring(0, idx), line.substring(idx + 1));
}
} finally {
bin.close();
}
return ImmutableMap.copyOf(out);
} catch (IOException e) {
log.log(Level.WARNING, "Symbol map not found: " + strongName, e);
// use empty symbol map to avoid repeated loads
return ImmutableMap.of();
}
}
});
/**
* Constructor, which takes a <code>symbolMaps</code> directory as its
* argument. Symbol maps can be generated using the <code>-extra</code> GWT
* compiler argument.
*/
@Inject
public StackTraceDeobfuscator(SymbolMapsDirectory symbolMapsDirectory) {
setSymbolMapsDirectory(symbolMapsDirectory);
}
/**
* Convenience method which resymbolizes an entire stack trace to extent
* possible.
*
* @param st the stack trace to resymbolize
* @param strongName the GWT permutation strong name
* @return a best effort resymbolized stack trace
*/
public StackTraceElement[] deobfuscateStackTrace(
String[] st, String strongName) {
StackTraceElement[] newSt = new StackTraceElement[st.length];
for (int i = 0; i < st.length; i++) {
newSt[i] = resymbolize(st[i], strongName);
}
return newSt;
}
/**
* Best effort resymbolization of a a single stack trace element.
*
* @param ste the stack trace element to resymbolize
* @param strongName the GWT permutation strong name
* @return the best effort resymbolized stack trace element
*/
public StackTraceElement resymbolize(String ste,
String strongName) {
Map<String, String> map = symbolMaps.get(strongName);
String symbolData = map == null ? null : map.get(ste);
if (symbolData != null) {
// jsniIdent, className, memberName, sourceUri, sourceLine
String[] parts =
Lists.newArrayList(Splitter.on(",").split(symbolData)).toArray(new String[0]);
if (parts.length == 5) {
String[] ref = parse(
parts[0].substring(0, parts[0].lastIndexOf(')') + 1));
String declaringClass = parts[1];
String methodName = parts[2];
// parts[3] contains the source file URI or "Unknown"
String filename = "Unknown".equals(parts[3]) ? null
: parts[3].substring(parts[3].lastIndexOf('/') + 1);
int lineNumber = 0; //ste.getLineNumber();
/*
* When lineNumber is zero, either because compiler.stackMode is not
* emulated or compiler.emulatedStack.recordLineNumbers is false, use
* the method declaration line number from the symbol map.
*/
if (lineNumber == 0) {
lineNumber = Integer.parseInt(parts[4]);
}
return new StackTraceElement(
declaringClass, methodName, filename, lineNumber);
}
}
return new StackTraceElement(
"UNKNOWN_CLASS", ste, "UNKNOWN_FILE", 0);
}
public void setSymbolMapsDirectory(SymbolMapsDirectory symbolMapsDirectory) {
// permutations are unique, no need to clear the symbolMaps hash map
this.symbolMapsDirectory = symbolMapsDirectory;
}
/**
* Extracts the declaring class and method name from a JSNI ref, or null if
* the information cannot be extracted.
*
* @see com.google.gwt.dev.util.JsniRef
* @param refString symbol map reference string
* @return a string array contains the declaring class and method name, or
* null when the regex match fails
*/
private String[] parse(String refString) {
Matcher matcher = JSNI_REF_PATTERN.matcher(refString);
if (!matcher.matches()) {
return null;
}
String className = matcher.group(1);
String memberName = matcher.group(2);
String[] toReturn = new String[] {className, memberName};
return toReturn;
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.gwt;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* @author ohler@google.com (Christian Ohler)
*/
public class ZipSymbolMapsDirectory implements StackTraceDeobfuscator.SymbolMapsDirectory {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(ZipSymbolMapsDirectory.class.getName());
private final ZipFile zip;
private final String rootDir;
public ZipSymbolMapsDirectory(ZipFile zip, String rootDir) {
this.zip = zip;
this.rootDir = rootDir;
}
@Override
public InputStream getSymbolMapInputStream(String permutationStrongName) throws IOException {
String fileName = rootDir + "/" + permutationStrongName + ".symbolMap";
ZipEntry entry = zip.getEntry(fileName);
log.info("ZipEntry for " + fileName + " is " + entry);
if (entry == null) {
throw new IOException(fileName + " not found in " + zip);
}
return zip.getInputStream(entry);
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server;
/**
* Interface to variables for monitoring purposes.
*
* The methods never throw exceptions; they log at level WARNING instead. This
* is so that errors that occur while recording monitoring information don't
* interfere with request processing. Even the invalid counter name
* {@code null} doesn't lead to an exception.
*
* Counter names with invalid characters will be ignored and logged, or
* converted to valid counter names (and possibly logged). Which characters are
* permitted depends on the implementation.
*
* @author ohler@google.com (Christian Ohler)
*/
public interface MonitoringVars {
final MonitoringVars NULL_IMPL = new MonitoringVars() {
@Override public void incrementCounter(String name) {}
@Override public void incrementCounter(String name, long increment) {}
};
void incrementCounter(String name);
void incrementCounter(String name, long increment);
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.writebatch;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.walkaround.util.server.RetryHelper.PermanentFailure;
/**
* Messages used in {@link BatchingUpdateProcessor}.
*
* @author ohler@google.com (Christian Ohler)
*/
// Package-private because only BatchingUpdateProcessor needs access.
class Messages {
private Messages() {}
/* (ohler-java-generate-union-type "<R>"
'(Message nil
((YourTurnMessage nil nil)
(ResultMessage ((R result nil)) nil)
(PermanentFailureMessage ((PermanentFailure failure nil)) nil)))) */
public enum MessageType {
YOUR_TURN,
RESULT,
PERMANENT_FAILURE;
}
public static abstract class Message<R> {
// Package-private so that no subclasses can be added outside this package.
Message() {
}
public abstract MessageType getType();
public boolean isYourTurnMessage() {
return false;
}
public boolean isResultMessage() {
return false;
}
public boolean isPermanentFailureMessage() {
return false;
}
public YourTurnMessage<R> asYourTurnMessage() {
throw new ClassCastException("Attempt to call asYourTurnMessage() on " + this);
}
public ResultMessage<R> asResultMessage() {
throw new ClassCastException("Attempt to call asResultMessage() on " + this);
}
public PermanentFailureMessage<R> asPermanentFailureMessage() {
throw new ClassCastException("Attempt to call asPermanentFailureMessage() on " + this);
}
}
public static class YourTurnMessage<R> extends Message<R> {
// Package-private so that no subclasses can be added outside this package.
YourTurnMessage() {
}
@Override public String toString() {
return "YourTurnMessage()";
}
@Override public boolean equals(Object o) {
return o != null && o.getClass() == YourTurnMessage.class;
}
@Override public int hashCode() {
return Objects.hashCode(YourTurnMessage.class);
}
@Override public MessageType getType() {
return MessageType.YOUR_TURN;
}
@Override public boolean isYourTurnMessage() {
return true;
}
@Override public YourTurnMessage<R> asYourTurnMessage() {
return this;
}
public static <R> YourTurnMessage<R> of() {
return new YourTurnMessage<R>();
}
}
public static class ResultMessage<R> extends Message<R> {
private final R result;
// Package-private so that no subclasses can be added outside this package.
ResultMessage(R result) {
Preconditions.checkNotNull(result, "Null result");
this.result = result;
}
public R getResult() {
return result;
}
@Override public String toString() {
return "ResultMessage("
+ result
+ ")";
}
@Override public boolean equals(Object o) {
if (o == null) return false;
if (o == this) return true;
if (!(o.getClass() == ResultMessage.class)) return false;
ResultMessage<?> other = (ResultMessage<?>) o;
return result.equals(other.result);
}
@Override public int hashCode() {
return Objects.hashCode(ResultMessage.class, result);
}
@Override public MessageType getType() {
return MessageType.RESULT;
}
@Override public boolean isResultMessage() {
return true;
}
@Override public ResultMessage<R> asResultMessage() {
return this;
}
public static <R> ResultMessage<R> of(R result) {
return new ResultMessage<R>(result);
}
}
public static class PermanentFailureMessage<R> extends Message<R> {
private final PermanentFailure failure;
// Package-private so that no subclasses can be added outside this package.
PermanentFailureMessage(PermanentFailure failure) {
Preconditions.checkNotNull(failure, "Null failure");
this.failure = failure;
}
public PermanentFailure getFailure() {
return failure;
}
@Override public String toString() {
return "PermanentFailureMessage("
+ failure
+ ")";
}
@Override public boolean equals(Object o) {
if (o == null) return false;
if (o == this) return true;
if (!(o.getClass() == PermanentFailureMessage.class)) return false;
PermanentFailureMessage<?> other = (PermanentFailureMessage<?>) o;
return failure.equals(other.failure);
}
@Override public int hashCode() {
return Objects.hashCode(PermanentFailureMessage.class, failure);
}
@Override public MessageType getType() {
return MessageType.PERMANENT_FAILURE;
}
@Override public boolean isPermanentFailureMessage() {
return true;
}
@Override public PermanentFailureMessage<R> asPermanentFailureMessage() {
return this;
}
public static <R> PermanentFailureMessage<R> of(PermanentFailure failure) {
return new PermanentFailureMessage<R>(failure);
}
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.writebatch;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.walkaround.util.server.RetryHelper;
import com.google.walkaround.util.server.RetryHelper.PermanentFailure;
import com.google.walkaround.util.server.RetryHelper.RetryableFailure;
import com.google.walkaround.util.server.writebatch.Messages.Message;
import com.google.walkaround.util.server.writebatch.Messages.PermanentFailureMessage;
import com.google.walkaround.util.server.writebatch.Messages.ResultMessage;
import com.google.walkaround.util.server.writebatch.Messages.YourTurnMessage;
import com.google.walkaround.util.server.writebatch.UpdateTransaction.BatchTooLargeException;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Processes updates in a way that batches transactions whenever there are
* multiple concurrent requests from different threads.
*
* This class is thread-safe (and only useful if used from multiple threads).
*
* Usage: Keep one BatchingUpdateProcessor per shared object. The
* TransactionFactory argument of the processor defines, through the
* UpdateTransaction implementation that it returns, how the shared objects
* behave and how they are stored and updated. Incoming request handlers should
* get the BatchingUpdateProcessor p that is responsible for the object to be
* modified, create an object of type U that specifies the change to be made,
* and invoke p.processUpdate(U). The BatchingUpdateProcessor will serialize
* all concurrent calls to p.processUpdate() and turn them into sequential calls
* to a transaction object.
*
* The BatchingUpdateProcessor first calls TransactionFactory.beginTransaction()
* to create a new transaction tx, then tx.processUpdate() once for each update,
* and finally tx.commit().
*
* Once tx.commit() returns, each call to p.processUpdate() in the request
* threads returns the UpdateResult returned by the corresponding call to
* tx.processUpdate(). Results for rejected updates may be returned to the
* request thread immediately rather than after commit().
*
* If TransactionFactory.beginTransaction(), UpdateTransaction.processUpdate()
* or UpdateTransaction.commit() throw a RetryableFailure, the
* BatchingUpdateProcessor will retry, according to the strategy implemented by
* the RetryHelper argument, by starting another transaction through
* TransactionFactory.beginTransaction() and repeating the above procedure.
* Rejected updates may not be retried.
*
*
* If any method on an object of this type throws a RuntimeException, the object
* must be discarded as its internal state may be corrupted. If any method
* throws an Error, the entire JVM should be terminated, as threads may be
* deadlocked or otherwise wedged. If a method throws a checked exception, on
* the other hand, the object's state is still valid.
*
* @author ohler@google.com (Christian Ohler)
*
* @param <U> type of update
* @param <R> type of result of an update
* @param <T> type of transaction
*/
public class BatchingUpdateProcessor<U, R extends UpdateResult, T extends UpdateTransaction<U, R>> {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(BatchingUpdateProcessor.class.getName());
private class QueueItem {
private final Thread thread;
private final RestrictedChannel<R> channel = new RestrictedChannel<R>();
private final U update;
public QueueItem(Thread thread, U update) {
Preconditions.checkNotNull(thread, "Null thread");
Preconditions.checkNotNull(update, "Null update");
this.thread = thread;
this.update = update;
}
public Thread getThread() {
return thread;
}
public RestrictedChannel<R> getChannel() {
return channel;
}
public U getUpdate() {
return update;
}
@Override public String toString() {
return "QueueItem(" + thread + ", " + channel + ", " + update + ")";
}
}
// A nontrivial invariant that we maintain is
//
// worker == null implies waitingItems.isEmpty()
//
// or, reading it the other way, "if there are waiting items, then worker is
// non-null". This invariant guarantees that we don't end up with waiting
// items with no worker to take care of them.
private final TransactionFactory<R, T> txFactory;
private final RetryHelper retryHelper;
private final Object lock = new Object();
// Concurrent so that we can remove rejected requests with no synchronization.
// Additions have to happen under the lock. (The invariant also implies that
// synchronization is needed for additions but not removals.)
private final ConcurrentLinkedQueue<QueueItem> waitingItems =
new ConcurrentLinkedQueue<QueueItem>();
private Thread worker = null;
// If this is non-null, the updater is unusable because its state may be corrupted.
private volatile Throwable corrupted = null;
public BatchingUpdateProcessor(TransactionFactory<R, T> txFactory,
RetryHelper retryHelper) {
Preconditions.checkNotNull(txFactory, "Null txFactory");
Preconditions.checkNotNull(retryHelper, "Null retryHelper");
this.txFactory = txFactory;
this.retryHelper = retryHelper;
}
@Override public String toString() {
return "BatchingUpdateProcessor(" + (corrupted == null ? "" : corrupted + ", ")
+ worker + ", " + waitingItems.size() + " waiting, " + waitingItems.peek() + ")";
}
private void setCorrupted(Throwable t) {
log.log(Level.SEVERE, this + ": Corrupted", t);
corrupted = t;
}
private void assertWorker() {
Preconditions.checkState(worker == Thread.currentThread(),
"%s: Thread %s assumed it was the worker", this, Thread.currentThread());
}
public R processUpdate(U update) throws PermanentFailure {
try {
return doProcessUpdate(update);
} catch (RuntimeException e) {
// It's possible that this RuntimeException left the processor in a state
// where no thread feels responsible for doing any work any more, thus
// leaving the threads that are currently waiting deadlocked. (Future
// requests won't have this problem because our contract says that the
// caller has to discard the updater after a RuntimeException.) We could
// try to resolve the deadlock by sending a corruption notification
// message to all waitingItems. A simpler alternative would be to rely on
// App Engine's 30-second timeout to kill the hanging threads, but I don't
// think that works for servers. For now, we throw an Error, in the hope
// that this will terminate the JVM.
setCorrupted(e);
throw new Error("RuntimeException from doProcessUpdate()", e);
} catch (Error e) {
setCorrupted(e);
throw e;
}
}
private R doProcessUpdate(U update) throws PermanentFailure {
// TODO(ohler): reject if queue is too long
log.info(this + ": processUpdate(" + update + ")");
QueueItem item = new QueueItem(Thread.currentThread(), update);
synchronized (lock) {
if (corrupted != null) {
// This should be unnecessary since the contract says that we shouldn't be called any more
// after a RuntimeException, but that's easy to get wrong, so let's be defensive.
throw new Error("Updater is corrupted: " + this, corrupted);
}
log.info(this + ": doProcessUpdate(): waitingItems=" + waitingItems);
if (worker == null) {
log.info(this + ": doProcessUpdate(): no worker active, will become worker");
worker = Thread.currentThread();
item.getChannel().send(YourTurnMessage.<R>of());
} else {
log.info(this + ": doProcessUpdate(): will wait for current worker: " + worker);
}
waitingItems.add(item);
}
log.info(this + ": doProcessUpdate(): waiting for message");
Message<R> message = item.getChannel().receive();
log.info(this + ": doProcessUpdate(): message=" + message);
if (message.isYourTurnMessage()) {
log.info(this + ": doProcessUpdate(): became worker");
assertWorker();
return doWorkAndReturnResult(item);
} else {
log.info(this + ": doProcessUpdate(): piggybacked, got result " + message);
return handleResultMessage(message);
}
}
private R handleResultMessage(Message<R> message) throws PermanentFailure {
log.info(this + ": handleResultMessage(" + message + ")");
if (message.isYourTurnMessage()) {
throw new AssertionError(this + ": Expected result message, not " + message);
} else if (message.isResultMessage()) {
return message.asResultMessage().getResult();
} else if (message.isPermanentFailureMessage()) {
throw new PermanentFailure("Worker thread reported PermanentFailure",
message.asPermanentFailureMessage().getFailure());
} else {
throw new AssertionError(this + ": Unexpected message type: " + message);
}
}
private R doWorkAndReturnResult(QueueItem item) throws PermanentFailure {
doWork();
Preconditions.checkState(!item.getChannel().isEmpty(), "%s", item);
log.info(this + ": doWorkAndReturnResult(): getting message");
Message<R> message = item.getChannel().receive();
log.info(this + ": doWorkAndReturnResult(): message=" + message);
return handleResultMessage(message);
}
private List<QueueItem> removeWaitingItems(int count) {
ImmutableList.Builder<QueueItem> b = ImmutableList.builder();
log.info(this + ": removeWaitingItems(): removing " + count + " waiting items from "
+ waitingItems);
for (int i = 0; i < count; i++) {
assertWorker();
b.add(waitingItems.remove());
}
List<QueueItem> removedItems = b.build();
log.info(this + ": removeWaitingItems(): removed: " + removedItems);
log.info(this + ": removeWaitingItems(): remaining: " + waitingItems);
return removedItems;
}
private class WorkerBody implements RetryHelper.VoidBody {
private final List<Message<R>> messagesToSend;
private WorkerBody(List<Message<R>> messagesToSend) {
this.messagesToSend = messagesToSend;
}
@Override public String toString() {
return "WorkerBody(" + BatchingUpdateProcessor.this + ")";
}
private void dropRequest(Iterator<QueueItem> iterator, QueueItem item, Message<R> m) {
log.info("doWork(): dropping request " + item + " with message " + m);
iterator.remove();
item.getChannel().send(m);
}
private void processItems(T tx) throws RetryableFailure, PermanentFailure {
Iterator<QueueItem> iterator = waitingItems.iterator();
Preconditions.checkState(iterator.hasNext(), "%s", waitingItems);
int rejected = 0;
while (iterator.hasNext()) {
QueueItem next = iterator.next();
log.info("doWork(): next=" + next);
R result;
try {
result = tx.processUpdate(next.getUpdate());
} catch (BatchTooLargeException e) {
if (messagesToSend.isEmpty() && rejected == 0) {
throw new RuntimeException(tx + " rejected the first update: " + next);
}
log.log(Level.INFO, "doWork(): batch too large", e);
break;
} catch (Error e) {
dropRequest(iterator, next, PermanentFailureMessage.<R>of(
new PermanentFailure("processUpdate() threw Error", e)));
throw e;
} catch (RuntimeException e) {
dropRequest(iterator, next, PermanentFailureMessage.<R>of(
new PermanentFailure("processUpdate() threw RuntimeException", e)));
throw e;
}
log.info("doWork(): result=" + result);
assertWorker();
if (result.isRejected()) {
log.info("doWork(): rejected");
dropRequest(iterator, next, ResultMessage.<R>of(result));
rejected++;
} else {
log.info("doWork(): accepted");
messagesToSend.add(ResultMessage.<R>of(result));
}
}
log.info("doWork(): " + rejected + " rejected, "
+ messagesToSend.size() + " messages to send");
}
@Override public void run() throws RetryableFailure, PermanentFailure {
messagesToSend.clear();
if (waitingItems.isEmpty()) {
return;
}
boolean commitCalled = false;
log.info("doWork(): calling beginTransaction()");
T tx = txFactory.beginTransaction();
log.info("doWork(): tx=" + tx);
try {
log.info("doWork(): waitingItems at start: " + waitingItems);
processItems(tx);
// We log waitingItems before and after to be able to see if anyone
// modified it concurrently.
log.info("doWork(): waitingItems at end but before removing: "
+ waitingItems);
log.info("doWork(): messagesToSend=" + messagesToSend);
log.info("doWork(): calling commit()");
commitCalled = true;
tx.commit();
log.info("doWork(): commit() done");
} catch (Error e) {
// Log this in case the finally clause below masks it with another exception.
log.log(Level.SEVERE, "Error in doWork()'s retry body", e);
throw e;
} catch (RuntimeException e) {
// Log this in case the finally clause below masks it with another exception.
log.log(Level.SEVERE, "RuntimeException in doWork()'s retry body", e);
throw e;
} finally {
if (!commitCalled) {
log.info("doWork(): calling rollback()");
tx.rollback();
log.info("doWork(): rollback() done");
}
}
}
}
private void addPermanentFailureMessages(List<Message<R>> messagesToSend,
PermanentFailure failure) {
Message<R> failureMessage = PermanentFailureMessage.<R>of(failure);
if (messagesToSend.isEmpty()) {
log.warning(this + ": messagesToSend is empty");
// This is a weird situation. Perhaps beginTransaction() threw a
// PermanentFailure. We drop at least one request (if there are any) to
// avoid infinite loops.
if (!waitingItems.isEmpty()) {
messagesToSend.add(failureMessage);
}
} else {
for (int i = 0; i < messagesToSend.size(); i++) {
messagesToSend.set(i, failureMessage);
}
}
}
private void doWork() throws PermanentFailure {
log.info(this + ": doWork(): begin");
Preconditions.checkState(!waitingItems.isEmpty(), "%s: waitingItems is empty", this);
// This list is parallel with a prefix of waitingItems: On success, the Nth message in this list
// will be sent to the Nth waitingItem. On PermanentFailure, the same number of waitingItems
// will be notified, but all with a failure message.
List<Message<R>> messagesToSend = Lists.newArrayList();
try {
retryHelper.run(new WorkerBody(messagesToSend));
} catch (PermanentFailure failure) {
log.log(Level.WARNING, "Permanent failure", failure);
addPermanentFailureMessages(messagesToSend, failure);
throw failure;
} catch (Error e) {
// Log this in case the finally clause below masks it with another exception.
log.log(Level.SEVERE, "Error in doWork()", e);
addPermanentFailureMessages(messagesToSend,
new PermanentFailure("Error in doWork()", e));
throw e;
} catch (RuntimeException e) {
// Log this in case the finally clause below masks it with another exception.
log.log(Level.SEVERE, "RuntimeException in doWork()", e);
addPermanentFailureMessages(messagesToSend,
new PermanentFailure("RuntimeException in doWork()", e));
throw e;
} finally {
// Note that it is possible that messagesToSend is empty: If the batch succeeded and
// all results were rejections.
List<QueueItem> removed = removeWaitingItems(messagesToSend.size());
synchronized (lock) {
assertWorker();
// NOTE(ohler): It is essential that this executes even if we throw PermanentFailure;
// otherwise, no thread will feel responsible for doing any work any more.
if (!waitingItems.isEmpty()) {
QueueItem item = waitingItems.element();
worker = item.getThread();
item.getChannel().send(YourTurnMessage.<R>of());
} else {
worker = null;
}
}
Preconditions.checkState(removed.size() == messagesToSend.size(), "%s %s",
removed.size(), messagesToSend.size());
for (int i = 0; i < removed.size(); i++) {
log.info(this + ": doWork(): sending result " + i);
removed.get(i).getChannel().send(messagesToSend.get(i));
}
}
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.writebatch;
import com.google.walkaround.util.server.RetryHelper.PermanentFailure;
import com.google.walkaround.util.server.RetryHelper.RetryableFailure;
/**
* A transaction that processes a sequence of updates. Multiple updates are
* processed in one transaction for efficiency.
*
* Instances will receive a number of calls to processUpdate() followed by
* exactly one call to either commit() or rollback().
*
* @author ohler@google.com (Christian Ohler)
*/
public interface UpdateTransaction<U, R extends UpdateResult> {
class BatchTooLargeException extends Exception {
private static final long serialVersionUID = 312635177505224710L;
public BatchTooLargeException() {
}
public BatchTooLargeException(String message) {
super(message);
}
public BatchTooLargeException(Throwable cause) {
super(cause);
}
public BatchTooLargeException(String message, Throwable cause) {
super(message, cause);
}
}
/**
* Take an update and processes it. Resulting changes to the datastore should
* only be committed in commit().
*
* It's valid for this function to mutate the update. If it does, the mutated
* update will be used for the next try (if there are any retries).
*
* May throw {@link BatchTooLargeException} to decline to process the update;
* {@link BatchingUpdateProcessor} will then process the update in the
* next transaction. The transaction remains usable after declining an update
* (still has to respond to processUpdate, commit, and rollback).
*
* The first call to this method on a given transaction must never throw
* {@link BatchTooLargeException}.
*/
R processUpdate(U update) throws BatchTooLargeException, RetryableFailure, PermanentFailure;
/**
* Commits the transaction. Called on successful completion of a sequence of
* updates. (Commits the underlying datastore transaction, or may roll it
* back if there is nothing to write, e.g., if the transaction has rejected
* all updates that it processed.)
*/
void commit() throws RetryableFailure, PermanentFailure;
/**
* Aborts the transaction. Called in case of an error. Should not throw
* exceptions as that might mask the exception that caused the original error.
* (Throwing RuntimeExceptions and Errors as a consequence of programming
* errors is fine, of course; but other errors should be logged rather than
* rethrown as RuntimeExceptions or Errors.)
*/
void rollback();
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.writebatch;
/**
* @author ohler@google.com (Christian Ohler)
*/
public interface UpdateResult {
/**
* A rejected update is an update that
*
* - didn't affect the application state (in memory or in the pending transaction)
* in an observable way
* - doesn't need to be retried if the transaction fails.
*/
boolean isRejected();
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.writebatch;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A blocking queue of T with some logging instrumentation and no
* InterruptedExceptions.
*
* @author ohler@google.com (Christian Ohler)
*/
public class Channel<T> {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(Channel.class.getName());
private final ArrayBlockingQueue<T> queue;
public Channel(int capacity) {
queue = new ArrayBlockingQueue<T>(capacity);
}
// Never returns, but has return type Error so that it can be called in a
// throws clause.
private Error interrupted(InterruptedException e) {
log.log(Level.SEVERE, "Interrupted", e);
Thread.currentThread().interrupt();
throw new Error("Interrupted", e);
}
public void send(T m) {
log.info(Thread.currentThread() + ": " + this + ": send(" + m + ")");
try {
queue.put(m);
} catch (InterruptedException e) {
throw interrupted(e);
}
log.info(Thread.currentThread() + ": " + this + ": send(): returning");
}
public T receive() {
log.info(Thread.currentThread() + ": " + this + ": receive()");
T result;
try {
result = queue.take();
} catch (InterruptedException e) {
throw interrupted(e);
}
log.info(Thread.currentThread() + ": " + this + ": receive(): returning " + result);
return result;
}
public boolean isEmpty() {
return queue.isEmpty();
}
@Override public String toString() {
int size = queue.size();
if (size <= 5) {
// TODO(ohler): should perhaps have a different toString() if capacity is 0
return "Channel(" + queue + ")";
} else {
return "Channel(" + size + ", " + queue.peek() + ")";
}
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.writebatch;
import com.google.walkaround.util.server.RetryHelper.PermanentFailure;
import com.google.walkaround.util.server.RetryHelper.RetryableFailure;
/**
* @author ohler@google.com (Christian Ohler)
*/
public interface TransactionFactory<R extends UpdateResult, T extends UpdateTransaction<?, R>> {
T beginTransaction() throws RetryableFailure, PermanentFailure;
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.writebatch;
import static com.google.walkaround.util.server.writebatch.Messages.*;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import org.waveprotocol.wave.model.util.Pair;
/**
* A Channel<Message<R>> of capacity 1 that only permits a specific sequence of
* message types and disallows send() until the previous message has been
* received.
*
* @author ohler@google.com (Christian Ohler)
*/
// Package-private because only BatchingUpdateProcessor needs access.
class RestrictedChannel<R> {
private enum State {
INITIAL,
YOUR_TURN_RECEIVED,
CLOSED;
}
private static final ImmutableMap<Pair<State, MessageType>, State> TRANSITIONS =
ImmutableMap.<Pair<State, MessageType>, State>builder()
.put(Pair.of(State.INITIAL, MessageType.RESULT), State.CLOSED)
.put(Pair.of(State.INITIAL, MessageType.YOUR_TURN), State.YOUR_TURN_RECEIVED)
.put(Pair.of(State.INITIAL, MessageType.PERMANENT_FAILURE), State.CLOSED)
.put(Pair.of(State.YOUR_TURN_RECEIVED, MessageType.RESULT), State.CLOSED)
// Pair.of(State.YOUR_TURN_RECEIVED, MessageType.YOUR_TURN)
.put(Pair.of(State.YOUR_TURN_RECEIVED, MessageType.PERMANENT_FAILURE), State.CLOSED)
// Pair.of(State.CLOSED, MessageType.RESULT)
// Pair.of(State.CLOSED, MessageType.YOUR_TURN)
// Pair.of(State.CLOSED, MessageType.PERMANENT_FAILURE)
.build();
private final Channel<Message<R>> channel = new Channel<Message<R>>(1);
private final Object lock = new Object();
// Guarded by lock.
private State state = State.INITIAL;
public RestrictedChannel() {
}
State nextState(State current, Message<R> m) {
State next = TRANSITIONS.get(Pair.of(current, m.getType()));
if (next == null) {
throw new AssertionError("Invalid message in state " + current + ": " + m);
}
return next;
}
public void send(Message<R> m) {
synchronized (lock) {
Preconditions.checkState(channel.isEmpty(), "Unexpected second message %s in channel %s",
m, this);
state = nextState(state, m);
channel.send(m);
}
}
public Message<R> receive() {
return channel.receive();
}
public boolean isEmpty() {
return channel.isEmpty();
}
@Override public String toString() {
return "RestrictedChannel(" + state + ", " + channel + ")";
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.auth;
/**
* Thrown when a security token is invalid.
*
* @author ohler@google.com (Christian Ohler)
*/
public class InvalidSecurityTokenException extends Exception {
private static final long serialVersionUID = 392668853965055966L;
public InvalidSecurityTokenException() {
}
public InvalidSecurityTokenException(String message) {
super(message);
}
public InvalidSecurityTokenException(Throwable cause) {
super(cause);
}
public InvalidSecurityTokenException(String message, Throwable cause) {
super(message, cause);
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.auth;
import org.apache.commons.codec.binary.Hex;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Random;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* Additional digest utilities.
*
* @author Daniel Danilatos (danilatos@google.com)
*/
public class DigestUtils2 {
public static final int SHA1_BLOCK_SIZE = 160 / 8;
private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
/**
* Immutable type-safe wrapper for a secret key.
*/
public static final class Secret {
public static Secret of(byte[] secret) {
return new Secret(Arrays.copyOf(secret, secret.length));
}
public static Secret generate(Random random) {
byte[] bytes = new byte[SHA1_BLOCK_SIZE];
random.nextBytes(bytes);
return new Secret(bytes);
}
private final byte[] data;
private final String asHex;
// NOTE(danilatos) This is not safe to be a public constructor
// as it does not copy the byte array.
private Secret(byte[] bytes) {
if (bytes.length > SHA1_BLOCK_SIZE) {
// TODO(danilatos): Verify that this is not a problem and then
// remove check.
throw new IllegalArgumentException("Secret length " + bytes.length +
" greater than block size " + SHA1_BLOCK_SIZE);
}
data = bytes;
asHex = Hex.encodeHexString(data);
}
public String getHexData() {
return asHex;
}
public byte[] getBytes() {
// Copy to avoid exposing the mutable array.
return Arrays.copyOf(data, data.length);
}
@Override
public String toString() {
// Purposefully don't actually show the secret data, in case it
// gets accidentally logged or revealed in the wrong place.
return "Secret(numBytes=" + data.length + ")";
}
}
/**
* Computes the RFC2104 SHA1 HMAC digest for the given message and secret.
*
* @param message the data to compute the digest of
*/
public static byte[] sha1hmac(Secret key, byte[] message) {
try {
// get an hmac_sha1 key from the raw key bytes
SecretKeySpec signingKey = new SecretKeySpec(key.data, HMAC_SHA1_ALGORITHM);
// get an hmac_sha1 Mac instance and initialize with the signing key
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
// compute the hmac on input data bytes
byte[] ret = mac.doFinal(message);
assert ret.length == SHA1_BLOCK_SIZE;
return ret;
} catch (InvalidKeyException e) {
throw new RuntimeException("Failed to generate HMAC", e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Failed to generate HMAC", e);
}
}
public static String hexHmac(Secret key, String str) {
return new String(Hex.encodeHex(
DigestUtils2.sha1hmac(key, str.getBytes())));
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.auth;
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.google.walkaround.util.server.auth.DigestUtils2.Secret;
import java.util.logging.Logger;
/**
* Creates and verifies security tokens.
*
* A token is generated from a visible part, a hidden part, and an HMAC. It has
* the form:
*
* token = (hmac(hidden, visible), visible)
*
* To paraphrase, the HMAC covers the visible and hidden parts. The visible
* part remains visible in the token after signing and can be recovered, while
* the hidden part only affects the HMAC and can not be recovered. Verifying a
* token requires knowing the hidden part.
*
* The hidden part doesn't have to be hard to predict (that's what the secret is
* for); it's merely a mechanism for producing different tokens that have the
* same visible part, or for adding more data to a token without making it
* bigger.
*
* @author ohler@google.com (Christian Ohler)
*/
public class SecurityTokenHelper {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(SecurityTokenHelper.class.getName());
private final Secret secret;
@Inject public SecurityTokenHelper(Secret secret) {
this.secret = secret;
}
private String getSignature(String hiddenPart, String visiblePart) {
Preconditions.checkArgument(!hiddenPart.contains("\0"),
"Hidden part contains NUL: %s", hiddenPart);
return DigestUtils2.hexHmac(secret, hiddenPart + "\0" + visiblePart);
}
/** Output is not URL-safe. */
public String createToken(String hiddenPart, String visiblePart) {
return getSignature(hiddenPart, visiblePart) + " " + visiblePart;
}
public String verifyAndGetVisiblePart(String expectedHiddenPart, String purportedToken)
throws InvalidSecurityTokenException {
int space = purportedToken.indexOf(' ');
if (space == -1) {
throw new InvalidSecurityTokenException("No space: " + purportedToken);
}
String actualVisiblePart = purportedToken.substring(space + 1);
String actualSignature = purportedToken.substring(0, space);
String expectedSignature = getSignature(expectedHiddenPart, actualVisiblePart);
if (!actualSignature.equals(expectedSignature)) {
throw new InvalidSecurityTokenException(
"Signature mismatch for actualVisiblePart " + actualVisiblePart
+ ", expectedHiddenPart " + expectedHiddenPart
+ " (expected signature " + expectedSignature + "): " + purportedToken);
}
return actualVisiblePart;
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Helps retry datastore transactions.
*
* @author ohler@google.com (Christian Ohler)
*/
public class RetryHelper {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(RetryHelper.class.getName());
public static class PermanentFailure extends Exception {
private static final long serialVersionUID = 593754888234966439L;
public PermanentFailure() {
}
public PermanentFailure(String message) {
super(message);
}
public PermanentFailure(Throwable cause) {
super(cause);
}
public PermanentFailure(String message, Throwable cause) {
super(message, cause);
}
}
public static class RetryableFailure extends Exception {
private static final long serialVersionUID = 881520674168876801L;
public RetryableFailure() {
}
public RetryableFailure(String message) {
super(message);
}
public RetryableFailure(Throwable cause) {
super(cause);
}
public RetryableFailure(String message, Throwable cause) {
super(message, cause);
}
}
public interface Body<R> {
R run() throws RetryableFailure, PermanentFailure;
}
public interface VoidBody {
void run() throws RetryableFailure, PermanentFailure;
}
public interface RetryStrategy {
/**
* Returns how long to sleep before retrying after the given exception has
* occurred. Negative values are not permitted. This should throw
* PermanentFailure if no more retries should be attempted.
*
* @param numRetries how many times the job has already been retried
* (not counting the initial attempt)
* @param millisSoFar how much total time has elapsed so far running this job
* @param exception the exception that was thrown
*/
long delayMillisBeforeRetry(int numRetries, long millisSoFar,
RetryableFailure exception) throws PermanentFailure;
}
public static RetryStrategy backoffStrategy(final long startDelayMillis,
final long maxDelayMillis, final long maxTotalTime) {
return new RetryStrategy() {
Random random = new Random();
long randomLong(long limit) {
return (long) (random.nextDouble() * limit);
}
@Override public long delayMillisBeforeRetry(int numRetries, long millisSoFar,
RetryableFailure e) throws PermanentFailure {
long nextDelay = randomLong(
Math.min(maxDelayMillis, startDelayMillis * (1 << numRetries))
+ 1);
if (millisSoFar + nextDelay < maxTotalTime) {
return nextDelay;
} else {
throw new PermanentFailure("Retry timeout exceeded: millisSoFar=" + millisSoFar
+ ", nextDelay=" + nextDelay + ", maxTotalTime=" + maxTotalTime, e);
}
}
};
}
public static final RetryHelper NO_RETRY = new RetryHelper(new RetryStrategy() {
@Override public long delayMillisBeforeRetry(int numRetries, long millisSoFar,
RetryableFailure exception) throws PermanentFailure {
throw new PermanentFailure("Retryable failure with NO_RETRY strategy", exception);
}
});
private final RetryStrategy retryStrategy;
public RetryHelper(RetryStrategy retryStrategy) {
Preconditions.checkNotNull(retryStrategy, "Null retryStrategy");
this.retryStrategy = retryStrategy;
}
public RetryHelper() {
this(backoffStrategy(5, 200, 15000));
}
private <R> R runBodyOnce(Body<R> b) throws RetryableFailure, PermanentFailure {
Stopwatch stopwatch = new Stopwatch().start();
log.info("Running body " + b);
boolean normalExit = false;
try {
R result = b.run();
normalExit = true;
return result;
} finally {
long duration = stopwatch.elapsedMillis();
log.info("Body exited " + (normalExit ? "normally" : "abnormally")
+ ", run time: " + duration + "ms");
}
}
public <R> R run(Body<R> b) throws PermanentFailure {
Stopwatch stopwatch = new Stopwatch().start();
for (int retries = 0; true; retries++) {
try {
return runBodyOnce(b);
} catch (RetryableFailure e) {
long elapsedMillis = stopwatch.elapsedMillis();
log.log(Level.WARNING, "Problem on retry " + retries + ", millis elapsed so far: "
+ elapsedMillis, e);
long delayMillis = retryStrategy.delayMillisBeforeRetry(retries, elapsedMillis, e);
if (delayMillis < 0) {
log.warning("Negative delay: " + delayMillis);
delayMillis = 100;
}
log.info("Sleeping for " + delayMillis + " millis");
try {
Thread.sleep(delayMillis);
} catch (InterruptedException e2) {
Thread.currentThread().interrupt();
throw new PermanentFailure("Interrupted while waiting to retry; "
+ retries + " tries total, " + stopwatch.elapsedMillis() + " millis elapsed", e2);
}
}
}
}
public void run(final VoidBody b) throws PermanentFailure {
run(new Body<Void>() {
@Override public Void run() throws PermanentFailure, RetryableFailure {
b.run();
return null;
}
@Override public String toString() {
return "VoidBodyWrapper(" + b + ")";
}
});
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.servlet;
import com.google.common.base.Throwables;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.walkaround.util.server.MonitoringVars;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
/**
* Collects some basic stats about which endpoints are requested and what
* responses we serve. These stats overlap with what the admin console
* displays, but the admin console's display is not integrated with our
* monitoring.
*
* @author ohler@google.com (Christian Ohler)
*/
@Singleton
public class RequestStatsFilter implements Filter {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(RequestStatsFilter.class.getName());
private final MonitoringVars monitoring;
@Inject public RequestStatsFilter(MonitoringVars monitoring) {
this.monitoring = monitoring;
}
@Override public void init(FilterConfig filterConfig) {}
@Override public void destroy() {}
// TODO(ohler): Upgrade our Java servlet implementation and eliminate this --
// HttpServletResponse comes with a getStatus() method in more recent
// versions.
private static class ResponseWrapper extends HttpServletResponseWrapper {
private int status;
public ResponseWrapper(HttpServletResponse wrapped) {
super(wrapped);
}
@Override public void sendError(int sc) throws IOException {
status = sc;
super.sendError(sc);
}
@Override public void sendError(int sc, String msg) throws IOException {
status = sc;
super.sendError(sc, msg);
}
@Override public void setStatus(int sc) {
status = sc;
super.setStatus(sc);
}
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain)
throws IOException {
HttpServletRequest request = (HttpServletRequest) req;
String methodAndUri = request.getMethod() + "-" + request.getRequestURI();
monitoring.incrementCounter("servlet-request-" + methodAndUri);
ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) resp);
try {
filterChain.doFilter(req, responseWrapper);
monitoring.incrementCounter("servlet-response-"
+ methodAndUri + "-" + responseWrapper.status);
} catch (Throwable t) {
monitoring.incrementCounter("servlet-uncaught-throwable-" + methodAndUri);
Throwables.propagateIfPossible(t, IOException.class);
throw Throwables.propagate(t);
}
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.servlet;
import javax.servlet.http.HttpServletResponse;
/**
* Thrown by server code when it detects that the client does not have permission.
*
* @author ohler@google.com (Christian Ohler)
*/
public class PermissionDeniedException extends HttpException {
private static final long serialVersionUID = 372093839240056814L;
public PermissionDeniedException() {
}
public PermissionDeniedException(String publicMessage) {
super(publicMessage);
}
public PermissionDeniedException(Throwable cause) {
super(cause);
}
public PermissionDeniedException(String publicMessage, Throwable cause) {
super(publicMessage, cause);
}
@Override public int getResponseCode() {
return HttpServletResponse.SC_FORBIDDEN;
}
@Override public String getPublicMessage() {
if (getMessage() == null) {
return "Permission denied";
} else {
return "Permission denied: " + getMessage();
}
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.servlet;
/**
* An exception that will be turned into a certain HTTP response code and message.
*
* Note that ServerExceptionFilter will log HttpExceptions at level INFO. When
* catching a more severe exception, make sure you log it with appropriate
* severity before rethrowing it as an HttpException.
*
* @author ohler@google.com (Christian Ohler)
*/
// TODO(ohler): Determine if it's worthwhile to make this a checked exception.
public abstract class HttpException extends RuntimeException {
public HttpException() {
}
public HttpException(String message) {
super(message);
}
public HttpException(Throwable cause) {
super(cause);
}
public HttpException(String message, Throwable cause) {
super(message, cause);
}
public abstract int getResponseCode();
/**
* A response message that does not reveal any information that we want to
* keep secret.
*/
public abstract String getPublicMessage();
}
| 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.walkaround.util.server.servlet;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Guice annotation for {@link HandlerServlet}.
*
* @author ohler@google.com (Christian Ohler)
*/
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface PrefixPathHandlers {}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.servlet;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @see HandlerServlet
* @author ohler@google.com (Christian Ohler)
*/
public abstract class AbstractHandler {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
// Perhaps this should be a 405 but who cares.
throw new BadRequestException("GET not supported");
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
// Perhaps this should be a 405 but who cares.
throw new BadRequestException("POST not supported");
}
// Other methods from javax.servlet.http.HttpServlet, like doPut etc., could
// be added here if we need them.
// TODO(ohler): Move the utilities below somewhere else.
// Apparently, HttpServletRequest.getParameterMap() returns a bare Map rather
// than Map<String, String[]>.
@SuppressWarnings("unchecked")
public static Map<String, String[]> getParameterMap(HttpServletRequest req) {
return req.getParameterMap();
}
public static String requireParameter(HttpServletRequest req, String key) {
String value = req.getParameter(key);
if (value == null) {
throw new BadRequestException("Missing parameter: " + key);
}
return value;
}
public static List<String> getParameters(HttpServletRequest req, String key) {
String[] values = getParameterMap(req).get(key);
return values == null ? ImmutableList.<String>of() : ImmutableList.copyOf(values);
}
public static String optionalParameter(HttpServletRequest req, String key,
@Nullable String defaultValue) {
String value = req.getParameter(key);
return value == null ? defaultValue : value;
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.servlet;
import javax.servlet.http.HttpServletResponse;
/**
* Thrown by server code when a resource does not exist (or if the user does not
* have access but we do not wish to reveal this information).
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class NotFoundException extends HttpException {
private static final long serialVersionUID = 272829532791826633L;
private static final String NOT_FOUND_MESSAGE = "We're sorry, this page either does not exist "
+ "or you do not have access to it.";
public static NotFoundException withInternalMessage(String message) {
return new NotFoundException(new Exception(message));
}
public NotFoundException() {
}
public NotFoundException(Throwable cause) {
super(cause);
}
@Override public int getResponseCode() {
return HttpServletResponse.SC_NOT_FOUND;
}
@Override public String getPublicMessage() {
return NOT_FOUND_MESSAGE;
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.servlet;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* A servlet that dispatches to {@link AbstractHandler} handlers bound through Guice.
*
* Also provides some default behavior like a default character encoding
*
* @author ohler@google.com (Christian Ohler)
*/
@Singleton
public class HandlerServlet extends HttpServlet {
private static final long serialVersionUID = 878017407495028316L;
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(HandlerServlet.class.getName());
private final Map<String, Provider<AbstractHandler>> exactPathHandlers;
private final Map<String, Provider<AbstractHandler>> prefixPathHandlers;
@Inject
public HandlerServlet(@ExactPathHandlers Map<String, Provider<AbstractHandler>> exactPathHandlers,
@PrefixPathHandlers Map<String, Provider<AbstractHandler>> prefixPathHandlers) {
this.exactPathHandlers = exactPathHandlers;
this.prefixPathHandlers = prefixPathHandlers;
}
private AbstractHandler getHandler(HttpServletRequest req) {
String requestUri = req.getRequestURI();
AbstractHandler handler = getHandlerProvider(requestUri).get();
log.info("getHandler(" + requestUri + ") = " + handler);
return handler;
}
private Provider<AbstractHandler> getHandlerProvider(String requestUri) {
// Try exact match.
{
Provider<AbstractHandler> handler = exactPathHandlers.get(requestUri);
if (handler != null) {
return handler;
}
}
// Try prefix match.
for (Map.Entry<String, Provider<AbstractHandler>> entry : prefixPathHandlers.entrySet()) {
if (requestUri.startsWith(entry.getKey())) {
return entry.getValue();
}
}
throw new RuntimeException("No handler found for: " + requestUri);
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
resp.setCharacterEncoding("UTF-8");
getHandler(req).doGet(req, resp);
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
resp.setCharacterEncoding("UTF-8");
getHandler(req).doPost(req, resp);
}
// Other methods from javax.servlet.http.HttpServlet, like doPut etc., could
// be added here if we need them.
}
| 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.walkaround.util.server.servlet;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Guice annotation for {@link HandlerServlet}.
*
* @author ohler@google.com (Christian Ohler)
*/
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface ExactPathHandlers {}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.servlet;
import javax.servlet.http.HttpServletResponse;
/**
* Thrown by server code when it detects that the client request was invalid.
*
* @author ohler@google.com (Christian Ohler)
*/
public class BadRequestException extends HttpException {
private static final long serialVersionUID = 219334514559267522L;
public static BadRequestException withInternalMessage(String message) {
return new BadRequestException(new Exception(message));
}
public BadRequestException() {
}
public BadRequestException(String publicMessage) {
super(publicMessage);
}
public BadRequestException(Throwable cause) {
super(cause);
}
public BadRequestException(String publicMessage, Throwable cause) {
super(publicMessage, cause);
}
@Override public int getResponseCode() {
return HttpServletResponse.SC_BAD_REQUEST;
}
@Override public String getPublicMessage() {
if (getMessage() == null) {
return "Bad request";
} else {
return "Bad request: " + getMessage();
}
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.servlet;
import javax.servlet.http.HttpServletResponse;
/**
* Thrown by server code when it can't serve the request right now but expects
* to be able to serve the same request later.
*
* @author ohler@google.com (Christian Ohler)
*/
public class TryAgainLaterException extends HttpException {
private static final long serialVersionUID = 423954225618154001L;
public TryAgainLaterException() {
}
public TryAgainLaterException(String publicMessage) {
super(publicMessage);
}
public TryAgainLaterException(Throwable cause) {
super(cause);
}
public TryAgainLaterException(String publicMessage, Throwable cause) {
super(publicMessage, cause);
}
@Override public int getResponseCode() {
return HttpServletResponse.SC_SERVICE_UNAVAILABLE;
}
@Override public String getPublicMessage() {
if (getMessage() == null) {
return "Try again later";
} else {
return "Try again later: " + getMessage();
}
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server.servlet;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* A servlet that redirects to another URL.
*
* @author ohler@google.com (Christian Ohler)
*/
public class RedirectServlet extends HttpServlet {
private static final long serialVersionUID = 930597932186069542L;
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(RedirectServlet.class.getName());
private final String destination;
public RedirectServlet(String destination) {
this.destination = destination;
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
log.info("redirecting from " + req.getRequestURL() + " to " + destination);
resp.sendRedirect(destination);
}
}
| Java |
/*
* Copyright 2011 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.walkaround.util.server;
import com.google.common.escape.CharEscaper;
import com.google.common.escape.CharEscaperBuilder;
/**
* Contains an html escaper.
*
* NOTE(danilatos):
* Stolen from http://code.google.com/p/gdata-java-client/source/browse/trunk/
* java/src/com/google/gdata/util/common/base/CharEscapers.java
*
* Delete if/when an appropriate HTML escaper is properly open sourced in guava.
*/
public class HtmlEscaper {
private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();
/**
* A fast {@link CharEscaper} that uses an array of replacement characters and
* a range of safe characters. It overrides {@link #escape(String)} to improve
* performance. Rough benchmarking shows that this almost doubles the speed
* when processing strings that do not require escaping (providing the escape
* test itself is efficient).
*/
private abstract static class FastCharEscaper extends CharEscaper {
protected final char[][] replacements;
protected final int replacementLength;
protected final char safeMin;
protected final char safeMax;
public FastCharEscaper(char[][] replacements, char safeMin, char safeMax) {
this.replacements = replacements;
this.replacementLength = replacements.length;
this.safeMin = safeMin;
this.safeMax = safeMax;
}
/** Overridden for performance (see {@link FastCharEscaper}). */
@Override public String escape(String s) {
int slen = s.length();
for (int index = 0; index < slen; index++) {
char c = s.charAt(index);
if ((c < replacementLength && replacements[c] != null)
|| c < safeMin || c > safeMax) {
return escapeSlow(s, index);
}
}
return s;
}
}
/**
* Escaper for HTML character escaping, contains both an array and a
* backup function. We're not overriding the array decorator because we
* want to keep this as fast as possible, so no calls to super.escape first.
*/
private static class HtmlCharEscaper extends FastCharEscaper {
public HtmlCharEscaper(char[][] replacements) {
super(replacements, Character.MIN_VALUE, '~');
}
@Override protected char[] escape(char c) {
// First check if our array has a valid escaping.
if (c < replacementLength) {
char[] r = replacements[c];
if (r != null) {
return r;
}
}
// ~ is ASCII 126, the highest value char that does not need
// to be escaped
if (c <= safeMax) {
return null;
}
int index;
if (c < 1000) {
index = 4;
} else if (c < 10000) {
index = 5;
} else {
index = 6;
}
char[] result = new char[index + 2];
result[0] = '&';
result[1] = '#';
result[index + 1] = ';';
// to avoid the division and modulo operators.
int intValue = c;
for (; index > 1; index--) {
result[index] = HEX_DIGITS[intValue % 10];
intValue /= 10;
}
return result;
}
}
public static final CharEscaper HTML_ESCAPER = new HtmlCharEscaper(new CharEscaperBuilder()
.addEscape('"', """)
.addEscape('\'', "'")
.addEscape('&', "&")
.addEscape('<', "<")
.addEscape('>', ">")
.addEscape('\u00A0', " ")
.addEscape('\u00A1', "¡")
.addEscape('\u00A2', "¢")
.addEscape('\u00A3', "£")
.addEscape('\u00A4', "¤")
.addEscape('\u00A5', "¥")
.addEscape('\u00A6', "¦")
.addEscape('\u00A7', "§")
.addEscape('\u00A8', "¨")
.addEscape('\u00A9', "©")
.addEscape('\u00AA', "ª")
.addEscape('\u00AB', "«")
.addEscape('\u00AC', "¬")
.addEscape('\u00AD', "­")
.addEscape('\u00AE', "®")
.addEscape('\u00AF', "¯")
.addEscape('\u00B0', "°")
.addEscape('\u00B1', "±")
.addEscape('\u00B2', "²")
.addEscape('\u00B3', "³")
.addEscape('\u00B4', "´")
.addEscape('\u00B5', "µ")
.addEscape('\u00B6', "¶")
.addEscape('\u00B7', "·")
.addEscape('\u00B8', "¸")
.addEscape('\u00B9', "¹")
.addEscape('\u00BA', "º")
.addEscape('\u00BB', "»")
.addEscape('\u00BC', "¼")
.addEscape('\u00BD', "½")
.addEscape('\u00BE', "¾")
.addEscape('\u00BF', "¿")
.addEscape('\u00C0', "À")
.addEscape('\u00C1', "Á")
.addEscape('\u00C2', "Â")
.addEscape('\u00C3', "Ã")
.addEscape('\u00C4', "Ä")
.addEscape('\u00C5', "Å")
.addEscape('\u00C6', "Æ")
.addEscape('\u00C7', "Ç")
.addEscape('\u00C8', "È")
.addEscape('\u00C9', "É")
.addEscape('\u00CA', "Ê")
.addEscape('\u00CB', "Ë")
.addEscape('\u00CC', "Ì")
.addEscape('\u00CD', "Í")
.addEscape('\u00CE', "Î")
.addEscape('\u00CF', "Ï")
.addEscape('\u00D0', "Ð")
.addEscape('\u00D1', "Ñ")
.addEscape('\u00D2', "Ò")
.addEscape('\u00D3', "Ó")
.addEscape('\u00D4', "Ô")
.addEscape('\u00D5', "Õ")
.addEscape('\u00D6', "Ö")
.addEscape('\u00D7', "×")
.addEscape('\u00D8', "Ø")
.addEscape('\u00D9', "Ù")
.addEscape('\u00DA', "Ú")
.addEscape('\u00DB', "Û")
.addEscape('\u00DC', "Ü")
.addEscape('\u00DD', "Ý")
.addEscape('\u00DE', "Þ")
.addEscape('\u00DF', "ß")
.addEscape('\u00E0', "à")
.addEscape('\u00E1', "á")
.addEscape('\u00E2', "â")
.addEscape('\u00E3', "ã")
.addEscape('\u00E4', "ä")
.addEscape('\u00E5', "å")
.addEscape('\u00E6', "æ")
.addEscape('\u00E7', "ç")
.addEscape('\u00E8', "è")
.addEscape('\u00E9', "é")
.addEscape('\u00EA', "ê")
.addEscape('\u00EB', "ë")
.addEscape('\u00EC', "ì")
.addEscape('\u00ED', "í")
.addEscape('\u00EE', "î")
.addEscape('\u00EF', "ï")
.addEscape('\u00F0', "ð")
.addEscape('\u00F1', "ñ")
.addEscape('\u00F2', "ò")
.addEscape('\u00F3', "ó")
.addEscape('\u00F4', "ô")
.addEscape('\u00F5', "õ")
.addEscape('\u00F6', "ö")
.addEscape('\u00F7', "÷")
.addEscape('\u00F8', "ø")
.addEscape('\u00F9', "ù")
.addEscape('\u00FA', "ú")
.addEscape('\u00FB', "û")
.addEscape('\u00FC', "ü")
.addEscape('\u00FD', "ý")
.addEscape('\u00FE', "þ")
.addEscape('\u00FF', "ÿ")
.addEscape('\u0152', "Œ")
.addEscape('\u0153', "œ")
.addEscape('\u0160', "Š")
.addEscape('\u0161', "š")
.addEscape('\u0178', "Ÿ")
.addEscape('\u0192', "ƒ")
.addEscape('\u02C6', "ˆ")
.addEscape('\u02DC', "˜")
.addEscape('\u0391', "Α")
.addEscape('\u0392', "Β")
.addEscape('\u0393', "Γ")
.addEscape('\u0394', "Δ")
.addEscape('\u0395', "Ε")
.addEscape('\u0396', "Ζ")
.addEscape('\u0397', "Η")
.addEscape('\u0398', "Θ")
.addEscape('\u0399', "Ι")
.addEscape('\u039A', "Κ")
.addEscape('\u039B', "Λ")
.addEscape('\u039C', "Μ")
.addEscape('\u039D', "Ν")
.addEscape('\u039E', "Ξ")
.addEscape('\u039F', "Ο")
.addEscape('\u03A0', "Π")
.addEscape('\u03A1', "Ρ")
.addEscape('\u03A3', "Σ")
.addEscape('\u03A4', "Τ")
.addEscape('\u03A5', "Υ")
.addEscape('\u03A6', "Φ")
.addEscape('\u03A7', "Χ")
.addEscape('\u03A8', "Ψ")
.addEscape('\u03A9', "Ω")
.addEscape('\u03B1', "α")
.addEscape('\u03B2', "β")
.addEscape('\u03B3', "γ")
.addEscape('\u03B4', "δ")
.addEscape('\u03B5', "ε")
.addEscape('\u03B6', "ζ")
.addEscape('\u03B7', "η")
.addEscape('\u03B8', "θ")
.addEscape('\u03B9', "ι")
.addEscape('\u03BA', "κ")
.addEscape('\u03BB', "λ")
.addEscape('\u03BC', "μ")
.addEscape('\u03BD', "ν")
.addEscape('\u03BE', "ξ")
.addEscape('\u03BF', "ο")
.addEscape('\u03C0', "π")
.addEscape('\u03C1', "ρ")
.addEscape('\u03C2', "ς")
.addEscape('\u03C3', "σ")
.addEscape('\u03C4', "τ")
.addEscape('\u03C5', "υ")
.addEscape('\u03C6', "φ")
.addEscape('\u03C7', "χ")
.addEscape('\u03C8', "ψ")
.addEscape('\u03C9', "ω")
.addEscape('\u03D1', "ϑ")
.addEscape('\u03D2', "ϒ")
.addEscape('\u03D6', "ϖ")
.addEscape('\u2002', " ")
.addEscape('\u2003', " ")
.addEscape('\u2009', " ")
.addEscape('\u200C', "‌")
.addEscape('\u200D', "‍")
.addEscape('\u200E', "‎")
.addEscape('\u200F', "‏")
.addEscape('\u2013', "–")
.addEscape('\u2014', "—")
.addEscape('\u2018', "‘")
.addEscape('\u2019', "’")
.addEscape('\u201A', "‚")
.addEscape('\u201C', "“")
.addEscape('\u201D', "”")
.addEscape('\u201E', "„")
.addEscape('\u2020', "†")
.addEscape('\u2021', "‡")
.addEscape('\u2022', "•")
.addEscape('\u2026', "…")
.addEscape('\u2030', "‰")
.addEscape('\u2032', "′")
.addEscape('\u2033', "″")
.addEscape('\u2039', "‹")
.addEscape('\u203A', "›")
.addEscape('\u203E', "‾")
.addEscape('\u2044', "⁄")
.addEscape('\u20AC', "€")
.addEscape('\u2111', "ℑ")
.addEscape('\u2118', "℘")
.addEscape('\u211C', "ℜ")
.addEscape('\u2122', "™")
.addEscape('\u2135', "ℵ")
.addEscape('\u2190', "←")
.addEscape('\u2191', "↑")
.addEscape('\u2192', "→")
.addEscape('\u2193', "↓")
.addEscape('\u2194', "↔")
.addEscape('\u21B5', "↵")
.addEscape('\u21D0', "⇐")
.addEscape('\u21D1', "⇑")
.addEscape('\u21D2', "⇒")
.addEscape('\u21D3', "⇓")
.addEscape('\u21D4', "⇔")
.addEscape('\u2200', "∀")
.addEscape('\u2202', "∂")
.addEscape('\u2203', "∃")
.addEscape('\u2205', "∅")
.addEscape('\u2207', "∇")
.addEscape('\u2208', "∈")
.addEscape('\u2209', "∉")
.addEscape('\u220B', "∋")
.addEscape('\u220F', "∏")
.addEscape('\u2211', "∑")
.addEscape('\u2212', "−")
.addEscape('\u2217', "∗")
.addEscape('\u221A', "√")
.addEscape('\u221D', "∝")
.addEscape('\u221E', "∞")
.addEscape('\u2220', "∠")
.addEscape('\u2227', "∧")
.addEscape('\u2228', "∨")
.addEscape('\u2229', "∩")
.addEscape('\u222A', "∪")
.addEscape('\u222B', "∫")
.addEscape('\u2234', "∴")
.addEscape('\u223C', "∼")
.addEscape('\u2245', "≅")
.addEscape('\u2248', "≈")
.addEscape('\u2260', "≠")
.addEscape('\u2261', "≡")
.addEscape('\u2264', "≤")
.addEscape('\u2265', "≥")
.addEscape('\u2282', "⊂")
.addEscape('\u2283', "⊃")
.addEscape('\u2284', "⊄")
.addEscape('\u2286', "⊆")
.addEscape('\u2287', "⊇")
.addEscape('\u2295', "⊕")
.addEscape('\u2297', "⊗")
.addEscape('\u22A5', "⊥")
.addEscape('\u22C5', "⋅")
.addEscape('\u2308', "⌈")
.addEscape('\u2309', "⌉")
.addEscape('\u230A', "⌊")
.addEscape('\u230B', "⌋")
.addEscape('\u2329', "⟨")
.addEscape('\u232A', "⟩")
.addEscape('\u25CA', "◊")
.addEscape('\u2660', "♠")
.addEscape('\u2663', "♣")
.addEscape('\u2665', "♥")
.addEscape('\u2666', "♦")
.toArray());
}
| Java |
/*
* Copyright 2011 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.walkaround.wave.client;
import com.google.common.base.Preconditions;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.walkaround.slob.client.ChangeDataParser;
import com.google.walkaround.slob.client.GenericOperationChannel.ReceiveOpChannel;
import com.google.walkaround.slob.shared.ChangeData;
import com.google.walkaround.slob.shared.MessageException;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.util.client.log.Logs.Level;
import com.google.walkaround.util.client.log.Logs.Log;
import com.google.walkaround.wave.client.GaeChannelDemuxer.GaeChannel;
import com.google.walkaround.wave.client.rpc.ChannelConnectService;
import org.waveprotocol.wave.client.common.util.JsoView;
import org.waveprotocol.wave.client.scheduler.Scheduler;
import org.waveprotocol.wave.client.scheduler.SchedulerInstance;
import org.waveprotocol.wave.client.scheduler.TimerService;
import org.waveprotocol.wave.model.util.CollectionUtils;
import org.waveprotocol.wave.model.util.IntMap;
import javax.annotation.Nullable;
/**
* Implementation of a {@link ReceiveOpChannel} based on Google App Engine's
* channel API.
*
* Converts a stream of possibly-missing, possibly-unordered, possibly-duplicated
* messages into a stream of in-order, consecutive, no-dup messages.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
// TODO(danilatos): Move the flaky layer into a separate class - possibly
// ChannelConnectService, as its callback interface would be sufficient as
// it stands now.
public abstract class GaeReceiveOpChannel<M>
implements ReceiveOpChannel<M>, GaeChannel {
private final Scheduler.IncrementalTask heartbeatTask = new Scheduler.IncrementalTask() {
@Override
public boolean execute() {
log.log(Level.DEBUG, "Heartbeat");
service.connect(signedSessionString, currentRevision, callback);
return true;
}
};
private final Scheduler.Task catchupTask = new Scheduler.Task() {
@Override
public void execute() {
maybeCatchup();
}
};
private final ChannelConnectService.Callback callback = new ChannelConnectService.Callback() {
@Override
public void onConnect(String token) {
log.log(Level.DEBUG, "connect onSuccess ", token);
Preconditions.checkState(initialToken == null, "Didn't even connect normally first!");
demuxer.connect(token);
}
@Override
public void onKnownHeadRevision(int headRevision) {
log.log(Level.DEBUG, "onKnownHeadRevision(", headRevision, "), ",
"old known=", knownHeadRevision, ", current=", currentRevision);
knownHeadRevision = Math.max(knownHeadRevision, headRevision);
if (knownHeadRevision > currentRevision) {
scheduleCatchup();
}
assert knownHeadRevision == currentRevision || scheduler.isScheduled(catchupTask);
}
@Override
public void onHistoryItem(int resultingRevision, ChangeData<JavaScriptObject> message) {
receiveUnorderedData(resultingRevision, message);
}
@Override
public void onConnectionError(Throwable e) {
// TODO(danilatos): Increase heartbeat interval
log.log(Level.WARNING, "onConnectionError ", e);
}
@Override
public void onFatalError(Throwable e) {
log.log(Level.WARNING, "onFatalError ", e);
}
};
/**
* Delay catchup in case we receive operations in the meantime.
*/
// TODO(danilatos): Flags for these values, and fuzz.
private static final int CATCHUP_DELAY_MILLIS = 3000;
private static final int HEARTBEAT_INTERVAL_MILLIS = 15 * 1000;
private final GaeChannelDemuxer demuxer = GaeChannelDemuxer.get();
private final TimerService scheduler = SchedulerInstance.getMediumPriorityTimer();
private final IntMap<ChangeData<JavaScriptObject>> pending = CollectionUtils.createIntMap();
private final SlobId objectId;
private final String signedSessionString;
private final ChannelConnectService service;
private final Log log;
private ReceiveOpChannel.Listener<M> listener;
private int currentRevision = 0;
private int knownHeadRevision = 0;
private int catchupRevision = 0;
/**
* Initial token provided in constructor, used once and then set to null.
* Subsequent tokens provided by the connect service callback.
*/
@Nullable private String initialToken;
@SuppressWarnings("unused") // used by native code
private JavaScriptObject socket;
public GaeReceiveOpChannel(SlobId objectId, String signedSessionString, String channelToken,
ChannelConnectService service, Log log) {
this.objectId = objectId;
this.signedSessionString = signedSessionString;
this.service = service;
this.log = log;
initialToken = channelToken;
}
@Override
public void connect(int revision, ReceiveOpChannel.Listener<M> listener) {
Preconditions.checkState(this.listener == null && initialToken != null);
this.listener = listener;
this.currentRevision = this.knownHeadRevision = revision;
log.log(Level.DEBUG, "connect, rev=", revision, ", token=", initialToken);
// Set up browser channel
demuxer.registerChannel(objectId.getId(), this);
demuxer.connect(initialToken);
initialToken = null;
// Send the first heartbeat immediately, to quickly catch up any initial missing
// ops, which might happen if the object is currently active.
scheduler.scheduleRepeating(heartbeatTask, 0, HEARTBEAT_INTERVAL_MILLIS);
}
@Override
public void disconnect() {
scheduler.cancel(heartbeatTask);
demuxer.deregisterChannel(objectId.getId());
}
private boolean receiving = false;
private boolean corruptedByException = false;
private void receiveUnorderedData(int resultingRevision, ChangeData<JavaScriptObject> message) {
Preconditions.checkState(!corruptedByException, "receiveUnorderedData called while corrupted");
Preconditions.checkState(!receiving, "receiveUnorderedData called re-entrantly");
receiving = true;
try {
unguardedReceiveUnorderedData(resultingRevision, message);
} catch (RuntimeException e) {
corruptedByException = true;
log.log(Level.WARNING, "Op channel is now corrupted", e);
throw e;
}
receiving = false;
}
private void unguardedReceiveUnorderedData(int resultingRevision,
ChangeData<JavaScriptObject> message) {
knownHeadRevision = Math.max(knownHeadRevision, resultingRevision);
if (resultingRevision <= currentRevision) {
log.log(Level.DEBUG, "Old dup at revision ", resultingRevision,
", current is now ", currentRevision);
return;
}
ChangeData<JavaScriptObject> existing = pending.get(resultingRevision);
if (existing != null) {
// Should not have pending data at a revision we could have pushed out.
assert resultingRevision > currentRevision + 1 : "should not have pending data";
// Sanity check
if (!existing.getClientId().equals(message.getClientId())) {
listener.onError(new Exception(
"Duplicates did not match at resultingRevision " + resultingRevision + ": "
+ existing + " vs " + message));
}
log.log(Level.DEBUG, "Dup message: ", message);
return;
}
if (resultingRevision > currentRevision + 1) {
pending.put(resultingRevision, message);
log.log(Level.DEBUG, "Missed message, currentRevision=", currentRevision,
" message revision=", resultingRevision);
scheduleCatchup();
return;
}
assert resultingRevision == currentRevision + 1 : "other cases should have been caught";
while (true) {
M data;
try {
data = parse(message);
} catch (MessageException e) {
listener.onError(e);
return;
}
log.log(Level.DEBUG, "Ordered op @", resultingRevision, " sid=", message.getClientId(),
", payload=", message.getPayload());
listener.onMessage(currentRevision + 1, message.getClientId().getId(), data);
currentRevision++;
int next = currentRevision + 1;
message = pending.get(next);
if (message != null) {
pending.remove(next);
} else {
break;
}
}
assert !pending.containsKey(currentRevision + 1);
}
private void scheduleCatchup() {
log.log(Level.DEBUG, "scheduleCatchup()");
// Check, to avoid resetting the delay.
if (!scheduler.isScheduled(catchupTask)) {
scheduler.scheduleDelayed(catchupTask, CATCHUP_DELAY_MILLIS);
}
}
private void maybeCatchup() {
// Check we're still out of date, and not already catching up.
if (knownHeadRevision > currentRevision && knownHeadRevision > catchupRevision) {
log.log(Level.DEBUG, "Catching up to " + knownHeadRevision);
catchupRevision = knownHeadRevision;
service.fetchHistory(signedSessionString, currentRevision, callback);
} else {
log.log(Level.DEBUG, "No need to catchup");
}
}
@Override
public void onMessage(JsoView changes) {
int len = (int) changes.getNumber("length");
for (int i = 0; i < len; i++) {
JsoView jso = changes.getJsoView(i);
int resultingRevision = (int) jso.getNumber("revision");
ChangeData<JavaScriptObject> message = ChangeDataParser.fromJson(jso);
log.log(Level.INFO, "Store message: ", message);
receiveUnorderedData(resultingRevision, message);
}
}
protected abstract M parse(ChangeData<JavaScriptObject> message)
throws MessageException;
}
| Java |
/*
* Copyright 2011 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.walkaround.wave.client;
import com.google.common.base.Preconditions;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.walkaround.slob.shared.MessageException;
import com.google.walkaround.util.client.log.Logs;
import com.google.walkaround.util.client.log.Logs.Level;
import com.google.walkaround.util.client.log.Logs.Log;
import org.waveprotocol.wave.client.common.util.JsoView;
import org.waveprotocol.wave.model.util.CollectionUtils;
import org.waveprotocol.wave.model.util.StringMap;
/**
* De-multiplexes object channels a client is listening to.
*
* Packets arrive with two keys, 'id' to identify the object, and 'm'
* containing the message payload.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class GaeChannelDemuxer {
// There should only ever be one global instance, or strange things will happen.
private GaeChannelDemuxer() {
}
private static final GaeChannelDemuxer INSTANCE = new GaeChannelDemuxer();
public static GaeChannelDemuxer get() {
return INSTANCE;
}
/**
* Channel that listens for messages to a specific object
*/
public interface GaeChannel {
void onMessage(JsoView data);
}
private final Log log = Logs.create("demuxer");
private final StringMap<GaeChannel> channels = CollectionUtils.createStringMap();
private String currentToken = null;
@SuppressWarnings("unused") // used by native code
private JavaScriptObject socket;
public void registerChannel(String objectId, GaeChannel channel) {
Preconditions.checkState(!channels.containsKey(objectId),
"Channel handler already registered for " + objectId);
channels.put(objectId, channel);
}
public void deregisterChannel(String objectId) {
Preconditions.checkState(channels.containsKey(objectId),
"Channel handler not registered for %s", objectId);
channels.remove(objectId);
}
public void connect(String token) {
if (!Preconditions.checkNotNull(token, "Null token").equals(currentToken)) {
log.log(Level.INFO, "Connecting with token ", token);
currentToken = token;
connectNative(token);
} else {
log.log(Level.DEBUG, "Already using same token, ignoring ", token);
}
}
private native void connectNative(String token) /*-{
var me = this;
var socket = this.@com.google.walkaround.wave.client.GaeChannelDemuxer::socket;
if (socket != null) {
socket.close();
}
channel = new $wnd.goog.appengine.Channel(token);
socket = channel.open();
this.@com.google.walkaround.wave.client.GaeChannelDemuxer::socket = socket;
socket.onopen = $entry(function() {
me.
@com.google.walkaround.wave.client.GaeChannelDemuxer::onOpened()
();
});
socket.onmessage = $entry(function(msg) {
me.
@com.google.walkaround.wave.client.GaeChannelDemuxer::onMessage(Ljava/lang/String;)
(msg.data);
});
socket.onerror = $entry(function(err) {
me.
@com.google.walkaround.wave.client.GaeChannelDemuxer::onError(ILjava/lang/String;)
(err.code, err.description);
});
socket.onclose = $entry(function() {
me.
@com.google.walkaround.wave.client.GaeChannelDemuxer::onClose()
();
});
}-*/;
@SuppressWarnings("unused") // called by native code
private void onOpened() {
log.log(Level.DEBUG, "onOpened ");
}
@SuppressWarnings("unused") // called by native code
private void onMessage(String data) {
log.log(Level.DEBUG, "onMessage data=", data);
if (data == null) {
log.log(Level.WARNING, "Null data on channel");
return;
}
try {
JsoView jso = JsUtil.eval(data);
if (!jso.containsKey("id") || !jso.containsKey("m")) {
throw new MessageException("Missing fields");
}
String id = jso.getString("id");
JsoView m = jso.getJsoView("m");
GaeChannel channel = channels.get(id);
if (channel == null) {
log.log(Level.WARNING, "No channel registered for object with id ", id);
return;
}
channel.onMessage(m);
} catch (MessageException e) {
log.log(Level.WARNING, "Bad data on channel ", data, " ", e);
}
}
@SuppressWarnings("unused") // called by native code
private void onError(int httpCode, String description) {
log.log(Level.WARNING, "onError code=", httpCode, " description=", description);
}
@SuppressWarnings("unused") // called by native code
private void onClose() {
log.log(Level.DEBUG, "onClose ");
}
}
| Java |
/*
* Copyright 2011 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.walkaround.wave.client;
import com.google.walkaround.slob.shared.MessageException;
import com.google.walkaround.wave.client.rpc.Rpc;
import com.google.walkaround.wave.client.rpc.Rpc.ConnectionState;
import com.google.walkaround.wave.client.rpc.Rpc.Method;
import com.google.walkaround.wave.client.rpc.Rpc.RpcCallback;
import org.waveprotocol.wave.client.scheduler.Scheduler.IncrementalTask;
import org.waveprotocol.wave.model.util.CollectionUtils;
/**
* @author danilatos@google.com (Daniel Danilatos)
*/
public class VersionChecker implements IncrementalTask {
private final Rpc rpc;
private final int thisClientVersion;
public VersionChecker(Rpc rpc, int thisClientVersion) {
this.rpc = rpc;
this.thisClientVersion = thisClientVersion;
}
@Override
public boolean execute() {
rpc.makeRequest(Method.GET, "version",
CollectionUtils.newStringMap("version", "" + thisClientVersion),
new RpcCallback() {
@Override
public void onSuccess(String data) throws MessageException {
int requiredClientVersion;
try {
requiredClientVersion = Integer.parseInt(data);
} catch (NumberFormatException nfe) {
throw new MessageException(nfe);
}
if (requiredClientVersion != thisClientVersion) {
// TODO(danilatos): Automatically refresh (after a random delay),
// if there's no unsaved data.
rpc.maybeSetConnectionState(ConnectionState.HARD_RELOAD);
}
}
@Override
public void onConnectionError(Throwable e) {
// do nothing
// TODO(danilatos): Back off
}
@Override
public void onFatalError(Throwable e) {
// do nothing
// TODO(danilatos): Back off
}
});
return true;
}
}
| Java |
/*
* Copyright 2011 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.walkaround.wave.client;
import com.google.walkaround.proto.Delta;
import com.google.walkaround.proto.DocumentDiffSnapshot;
import com.google.walkaround.proto.OperationBatch;
import com.google.walkaround.proto.ProtocolDocumentOperation;
import com.google.walkaround.proto.ProtocolDocumentOperation.Component;
import com.google.walkaround.proto.ProtocolDocumentOperation.Component.AnnotationBoundary;
import com.google.walkaround.proto.ProtocolDocumentOperation.Component.ElementStart;
import com.google.walkaround.proto.ProtocolDocumentOperation.Component.KeyValuePair;
import com.google.walkaround.proto.ProtocolDocumentOperation.Component.KeyValueUpdate;
import com.google.walkaround.proto.ProtocolDocumentOperation.Component.ReplaceAttributes;
import com.google.walkaround.proto.ProtocolDocumentOperation.Component.UpdateAttributes;
import com.google.walkaround.proto.ProtocolWaveletOperation;
import com.google.walkaround.proto.ProtocolWaveletOperation.MutateDocument;
import com.google.walkaround.proto.WalkaroundDocumentSnapshot;
import com.google.walkaround.proto.WalkaroundWaveletSnapshot;
import com.google.walkaround.proto.WaveletDiffSnapshot;
import com.google.walkaround.proto.jso.DeltaJsoImpl;
import com.google.walkaround.proto.jso.DocumentDiffSnapshotJsoImpl;
import com.google.walkaround.proto.jso.OperationBatchJsoImpl;
import com.google.walkaround.proto.jso.ProtocolDocumentOperationJsoImpl;
import com.google.walkaround.proto.jso.ProtocolDocumentOperationJsoImpl.ComponentJsoImpl;
import com.google.walkaround.proto.jso.ProtocolDocumentOperationJsoImpl.ComponentJsoImpl.AnnotationBoundaryJsoImpl;
import com.google.walkaround.proto.jso.ProtocolDocumentOperationJsoImpl.ComponentJsoImpl.ElementStartJsoImpl;
import com.google.walkaround.proto.jso.ProtocolDocumentOperationJsoImpl.ComponentJsoImpl.KeyValuePairJsoImpl;
import com.google.walkaround.proto.jso.ProtocolDocumentOperationJsoImpl.ComponentJsoImpl.KeyValueUpdateJsoImpl;
import com.google.walkaround.proto.jso.ProtocolDocumentOperationJsoImpl.ComponentJsoImpl.ReplaceAttributesJsoImpl;
import com.google.walkaround.proto.jso.ProtocolDocumentOperationJsoImpl.ComponentJsoImpl.UpdateAttributesJsoImpl;
import com.google.walkaround.proto.jso.ProtocolWaveletOperationJsoImpl;
import com.google.walkaround.proto.jso.ProtocolWaveletOperationJsoImpl.MutateDocumentJsoImpl;
import com.google.walkaround.proto.jso.WalkaroundDocumentSnapshotJsoImpl;
import com.google.walkaround.proto.jso.WalkaroundWaveletSnapshotJsoImpl;
import com.google.walkaround.proto.jso.WaveletDiffSnapshotJsoImpl;
import com.google.walkaround.wave.shared.MessageFactory;
/**
* Creates client side implementation of messages.
*
* @author zdwang@google.com (David Wang)
*/
public class MessageFactoryClient implements MessageFactory {
@Override
public OperationBatch createOperationBatch() {
return OperationBatchJsoImpl.create();
}
@Override
public ProtocolWaveletOperation createWaveOp() {
return ProtocolWaveletOperationJsoImpl.create();
}
@Override
public AnnotationBoundary createDocumentAnnotationBoundary() {
return AnnotationBoundaryJsoImpl.create();
}
@Override
public KeyValuePair createDocumentKeyValuePair() {
return KeyValuePairJsoImpl.create();
}
@Override
public KeyValueUpdate createDocumentKeyValueUpdate() {
return KeyValueUpdateJsoImpl.create();
}
@Override
public ProtocolDocumentOperation createDocumentOperation() {
return ProtocolDocumentOperationJsoImpl.create();
}
@Override
public Component createDocumentOperationComponent() {
return ComponentJsoImpl.create();
}
@Override
public ReplaceAttributes createDocumentReplaceAttributes() {
return ReplaceAttributesJsoImpl.create();
}
@Override
public MutateDocument createMutateDocument() {
return MutateDocumentJsoImpl.create();
}
@Override
public ElementStart createDocumentElementStart() {
return ElementStartJsoImpl.create();
}
@Override
public UpdateAttributes createDocumentUpdateAttributes() {
return UpdateAttributesJsoImpl.create();
}
@Override
public WalkaroundDocumentSnapshot createDocumentSnapshot() {
return WalkaroundDocumentSnapshotJsoImpl.create();
}
@Override
public WalkaroundWaveletSnapshot createWaveletSnapshot() {
return WalkaroundWaveletSnapshotJsoImpl.create();
}
@Override
public DocumentDiffSnapshot createDocumentDiffSnapshot() {
return DocumentDiffSnapshotJsoImpl.create();
}
@Override
public WaveletDiffSnapshot createWaveletDiffSnapshot() {
return WaveletDiffSnapshotJsoImpl.create();
}
@Override
public Delta createDelta() {
return DeltaJsoImpl.create();
}
}
| Java |
/*
* Copyright 2011 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.walkaround.wave.client;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.UIObject;
import org.waveprotocol.wave.client.common.util.DomHelper;
import org.waveprotocol.wave.client.common.util.DomHelper.JavaScriptEventListener;
import org.waveprotocol.wave.client.scheduler.Scheduler;
/**
* Simple debug menu
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class DebugMenu {
private final Element element;
public DebugMenu() {
element = Document.get().createDivElement();
element.setClassName("debug-menu");
}
public void install() {
Document.get().getBody().appendChild(element);
}
public void addItem(String text, final Scheduler.Task command) {
Element elem = Document.get().createAnchorElement();
elem.setInnerText(text);
DomHelper.registerEventHandler(elem, "click", new JavaScriptEventListener() {
@Override public void onJavaScriptEvent(String name, Event event) {
command.execute();
}
});
element.appendChild(elem);
}
public void setVisible(boolean visible) {
UIObject.setVisible(element, visible);
}
}
| Java |
/*
* Copyright 2011 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.walkaround.wave.client.profile;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.walkaround.wave.shared.ContactsService.Contact;
/**
* A JSO DTO for a Contact.
*
* @author hearnden@google.com (David Hearnden)
*/
public final class ContactJsoImpl extends JavaScriptObject implements Contact {
protected ContactJsoImpl() {}
@Override
public native String getAddress() /*-{
return this.a;
}-*/;
@Override
public native String getName() /*-{
return this.n;
}-*/;
@Override
public native String getPhotoId() /*-{
// String leading slash.
return this.p.substring(1);
}-*/;
}
| Java |
/*
* Copyright 2011 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.walkaround.wave.client.profile;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.walkaround.wave.shared.ContactsService.ContactList;
/**
* A JSO DTO for Contacts.
*
* @author hearnden@google.com (David Hearnden)
*/
public final class ContactListJsoImpl extends JavaScriptObject implements ContactList {
protected ContactListJsoImpl() {}
@Override
public native int size() /*-{
return this.length;
}-*/;
@Override
public native ContactJsoImpl get(int i) /*-{
return this[i];
}-*/;
}
| Java |
/*
* Copyright 2011 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.walkaround.wave.client.profile;
import com.google.common.base.Joiner;
import com.google.gwt.http.client.URL;
import com.google.walkaround.util.client.log.Logs;
import com.google.walkaround.util.client.log.Logs.Level;
import com.google.walkaround.util.client.log.Logs.Log;
import com.google.walkaround.wave.client.rpc.Rpc;
import com.google.walkaround.wave.shared.ContactsService;
import com.google.walkaround.wave.shared.ContactsService.Contact;
import com.google.walkaround.wave.shared.ContactsService.ContactList;
import com.google.walkaround.wave.shared.SharedConstants;
import org.waveprotocol.wave.client.account.Profile;
import org.waveprotocol.wave.client.account.ProfileListener;
import org.waveprotocol.wave.client.account.ProfileManager;
import org.waveprotocol.wave.client.scheduler.Scheduler.Task;
import org.waveprotocol.wave.client.scheduler.SchedulerInstance;
import org.waveprotocol.wave.client.scheduler.TimerService;
import org.waveprotocol.wave.model.util.CollectionUtils;
import org.waveprotocol.wave.model.util.CopyOnWriteSet;
import org.waveprotocol.wave.model.util.StringMap;
import org.waveprotocol.wave.model.wave.InvalidParticipantAddress;
import org.waveprotocol.wave.model.wave.ParticipantId;
import java.util.List;
import java.util.Random;
/**
* Uses a contacts service to provide profile information.
*
* @author hearnden@google.com (David Hearnden)
*/
public final class ContactsManager implements ProfileManager, ContactsService.Callback, Task {
/**
* A profile that can draw information from contacts.
*/
private class ProfileImpl implements Profile {
private final ParticipantId id;
// These fields start off as guesses, then get replaced with contact data.
private String firstName;
private String fullName;
private String photoUrl = SharedConstants.UNKNOWN_AVATAR_URL;
private ProfileImpl(ParticipantId id) {
this.id = id;
}
boolean updateWith(Contact contact) {
boolean changed = false;
if (contact.getName() != null) {
fullName = contact.getName();
int separator = fullName.indexOf(' ');
firstName = separator != -1 ? fullName.substring(0, separator) : fullName;
changed = true;
}
if (contact.getPhotoId() != null) {
photoUrl = "/photos?photoId=" + URL.encodeQueryString(contact.getPhotoId());
changed = true;
}
return changed;
}
@Override
public ParticipantId getParticipantId() {
return id;
}
@Override
public String getAddress() {
return id.getAddress();
}
@Override
public String getFirstName() {
if (firstName == null) {
guessNames();
}
return firstName;
}
@Override
public String getFullName() {
if (fullName == null) {
guessNames();
}
return fullName;
}
@Override
public String getImageUrl() {
return photoUrl;
}
private void guessNames() {
assert firstName == null || fullName == null; // Only called from lazy
// loading.
List<String> names = guessNames(id.getAddress());
if (firstName == null) {
firstName = names.get(0);
}
if (fullName == null) {
fullName = Joiner.on(' ').join(names);
}
}
private List<String> guessNames(String address) {
List<String> names = CollectionUtils.newArrayList();
String nameWithoutDomain = address.split("@")[0];
// Include empty names from fragment, so split with a -ve.
for (String fragment : nameWithoutDomain.split("[._]", -1)) {
if (!fragment.isEmpty()) {
names.add(capitalize(fragment));
}
}
// ParticipantId normalization, and empty name inclusion, implies names
// can not be empty.
assert !names.isEmpty();
return names;
}
private String capitalize(String s) {
return s.isEmpty() ? s : Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
}
/** Constructs a profile from nothing but a participant id. */
private ProfileImpl profileFromThinAir(ParticipantId id) {
return new ProfileImpl(id);
}
/** Constructs a profile from a contact. */
private ProfileImpl profileFromContact(Contact c) throws InvalidParticipantAddress {
ParticipantId id = ParticipantId.of(c.getAddress());
ProfileImpl profile = new ProfileImpl(id);
profile.updateWith(c);
return profile;
}
private static final Log LOG = Logs.create("contacts");
/** Maximum (total) number of contacts to fetch. */
// This is an arbitrary maximum. Contact data is fairly small (50-100 bytes of
// JSON per contact, which is ~100bytes per JS object on Chrome, ~400bytes per
// JS object on Firefox, so 2000 of these should be fine. The incremental
// benefit to the quality of this profile service from contacts in the feed
// beyond some large number (MAX_CONTACTS) is assumed to be small enough that
// such contacts can be ignored.
private static final int MAX_CONTACTS = 2000;
/** Number of contacts to fetch on each call. */
private static final int FETCH_SIZE = ContactsService.MAX_SIZE;
/** How long to wait before fetching all contacts again (every 30m). */
private static final int REFRESH_INTERVAL_MS = 30 * 60 * 1000;
private final ContactsService service;
private final TimerService timer;
private final Random random;
private final StringMap<Contact> contacts = CollectionUtils.createStringMap();
private final StringMap<ProfileImpl> profiles = CollectionUtils.createStringMap();
private final CopyOnWriteSet<ProfileListener> listeners = CopyOnWriteSet.create();
private int feedIndex = 1; // Contacts service is 1-based, not 0-based.
ContactsManager(ContactsService service, TimerService timer, Random random) {
this.service = service;
this.timer = timer;
this.random = random;
}
/**
* Creates a contacts manager. The manager will start fetching contacts
* immediately.
*/
public static ContactsManager create(Rpc rpc) {
ContactsService service = new RemoteContactsService(rpc);
TimerService timer = SchedulerInstance.getLowPriorityTimer();
ContactsManager manager = new ContactsManager(service, timer, new Random());
manager.fetchNext();
return manager;
}
@Override
public Profile getProfile(ParticipantId pid) {
String id = pid.getAddress();
ProfileImpl profile = profiles.get(id);
if (profile == null) {
if (contacts.containsKey(id)) {
try {
profile = profileFromContact(contacts.get(id));
} catch (InvalidParticipantAddress e) {
LOG.log(Level.WARNING, "Invalid contact address: ", contacts.get(id).getAddress());
contacts.remove(id);
profile = profileFromThinAir(pid);
}
} else {
profile = profileFromThinAir(pid);
}
profiles.put(id, profile);
}
return profile;
}
/**
* Adds contacts to the contact store, and updates any existing profiles.
*/
private void updateWith(ContactList someContacts) {
for (int i = 0; i < someContacts.size(); i++) {
Contact contact = someContacts.get(i);
String id = contact.getAddress();
if (id == null) {
// Empty contact; discard it.
continue;
}
contacts.put(id, contact);
ProfileImpl profile = profiles.get(id);
if (profile != null) {
profile.updateWith(contact);
fireUpdates(profile);
}
}
}
//
// Fetching.
//
private void fetchNext() {
timer.schedule(this);
}
private void refreshLater() {
feedIndex = 1;
timer.scheduleDelayed(this, (int) ((0.9 + 0.2 * random.nextDouble()) * REFRESH_INTERVAL_MS));
}
@Override
public void execute() {
assert feedIndex < MAX_CONTACTS;
LOG.log(Level.INFO, "Requesting " + FETCH_SIZE + " contacts");
service.fetch(feedIndex, Math.min(feedIndex + FETCH_SIZE, MAX_CONTACTS), this);
}
//
// ContactService callbacks.
//
@Override
public void onSuccess(ContactList result) {
LOG.log(Level.INFO, "Contact fetch succeeded with ", result.size(), " contacts");
updateWith(result);
feedIndex += result.size();
// Fetch more contacts?
if (result.size() == FETCH_SIZE) {
if (feedIndex < MAX_CONTACTS) {
fetchNext();
} else {
LOG.log(Level.INFO, "Finished fetching ", feedIndex, " contacts (max reached)");
refreshLater();
}
} else {
LOG.log(Level.INFO, "Finished fetching ", feedIndex, " contacts (no more contacts)");
refreshLater();
}
}
@Override
public void onFailure() {
LOG.log(Level.WARNING, "Contact fetch failed");
// Start again later.
refreshLater();
}
//
// Events.
//
@Override
public void addListener(ProfileListener listener) {
listeners.add(listener);
}
@Override
public void removeListener(ProfileListener listener) {
listeners.remove(listener);
}
private void fireUpdates(Profile... profiles) {
// Note: if this gets too large, this should be extracted into an
// incremental background task.
for (ProfileListener listener : listeners) {
for (int i = 0; i < profiles.length; i++) {
listener.onProfileUpdated(profiles[i]);
}
}
}
@Override
public boolean shouldIgnore(ParticipantId participantId) {
return false;
}
}
| Java |
/*
* Copyright 2011 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.walkaround.wave.client.profile;
import com.google.walkaround.slob.shared.MessageException;
import com.google.walkaround.util.client.log.Logs;
import com.google.walkaround.util.client.log.Logs.Level;
import com.google.walkaround.util.client.log.Logs.Log;
import com.google.walkaround.wave.client.rpc.Rpc;
import com.google.walkaround.wave.client.rpc.Rpc.Method;
import com.google.walkaround.wave.client.rpc.RpcUtil;
import com.google.walkaround.wave.shared.ContactsService;
import org.waveprotocol.wave.model.util.CollectionUtils;
import org.waveprotocol.wave.model.util.StringMap;
/**
* Provides a contacts service using AJAX rpcs.
*
* @author hearnden@google.com (David Hearnden)
*/
public final class RemoteContactsService implements ContactsService {
private static final Log LOG = Logs.create("contacts");
private static final String SERVICE_NAME = "contacts";
/** RPC worker. */
private final Rpc rpc;
public RemoteContactsService(Rpc rpc) {
this.rpc = rpc;
}
@Override
public void fetch(int from, int to, final Callback callback) {
StringMap<String> params = CollectionUtils.createStringMap();
params.put("from", Integer.toString(from));
params.put("to", Integer.toString(to));
rpc.makeRequest(Method.GET, SERVICE_NAME, params, new Rpc.RpcCallback() {
@Override
public void onSuccess(String data) throws MessageException {
callback.onSuccess(RpcUtil.evalPrefixed(data).<ContactListJsoImpl>cast());
}
@Override
public void onFatalError(Throwable e) {
LOG.log(Level.WARNING, "Contact fetch failed", e);
callback.onFailure();
}
@Override
public void onConnectionError(Throwable e) {
LOG.log(Level.WARNING, "Contact fetch failed", e);
callback.onFailure();
}
});
}
}
| Java |
/*
* Copyright 2011 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.walkaround.wave.client;
/**
* Sets the read state of the wave.
*
* @author hearnden@google.com (David Hearnden);
*/
public interface ReadStateService {
/** Sets the read state of this wave. */
void setReadState(boolean read);
}
| Java |
/*
* Copyright 2011 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.walkaround.wave.client;
import com.google.common.base.Preconditions;
import com.google.walkaround.slob.client.GenericOperationChannel;
import com.google.walkaround.slob.client.GenericOperationChannel.ReceiveOpChannel;
import com.google.walkaround.slob.client.GenericOperationChannel.SendOpService;
import com.google.walkaround.slob.client.TransformQueue.Transformer;
import com.google.walkaround.util.client.log.Logs.Level;
import com.google.walkaround.util.client.log.Logs.Log;
import org.waveprotocol.wave.client.scheduler.SchedulerInstance;
import org.waveprotocol.wave.concurrencycontrol.channel.OperationChannel;
import org.waveprotocol.wave.concurrencycontrol.client.MergingSequence;
import org.waveprotocol.wave.model.operation.OperationPair;
import org.waveprotocol.wave.model.operation.TransformException;
import org.waveprotocol.wave.model.operation.wave.Transform;
import org.waveprotocol.wave.model.operation.wave.WaveletOperation;
import org.waveprotocol.wave.model.util.CollectionUtils;
import org.waveprotocol.wave.model.version.HashedVersion;
import java.util.List;
import java.util.Queue;
/**
* Adapts GenericOperationChannel to implement wave's OperationChannel.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class WalkaroundOperationChannel implements OperationChannel {
private static int lastChannelId;
// NOTE(danilatos): Wavelet id would also work fine.
private final String channelId = "" + (++lastChannelId);
public interface SavedStateListener {
void unsaved(String channelId);
void saved(String channelId);
void turbulenced();
}
/**
* Wave requires {code VersionUpdateOp}s in the operation stream from the
* channel wherever a client acknowledgment occurred. We create a buffer that
* contains these ops for each ack, and null for each remote wavelet
* operation. We can't eagerly fill the buffer with the remote operations
* because those operations may need to be transformed further against
* subsequent client ops. So we should only e.g. {@link #peek()} at the very
* last minute.
*/
private final Queue<WaveletOperation> versionUpdatesBuffer = CollectionUtils.createQueue();
public static final boolean HACK_NO_INCOMING = false;
private final Transformer<WaveletOperation> transformer = new Transformer<WaveletOperation>() {
@Override
public OperationPair<WaveletOperation> transform(
WaveletOperation clientOp, WaveletOperation serverOp) {
try {
return Transform.transform(clientOp, serverOp);
} catch (TransformException e) {
throw new RuntimeException(e);
}
}
@Override
public List<WaveletOperation> compact(List<WaveletOperation> clientOps) {
MergingSequence m = new MergingSequence(clientOps);
m.optimise();
return m;
}
};
private final GenericOperationChannel.Listener<WaveletOperation> channelListener =
new GenericOperationChannel.Listener<WaveletOperation>() {
@Override
public void onError(Throwable e) {
logger.log(Level.WARNING, e);
savedStateListener.turbulenced();
}
@Override
public void onRemoteOp(WaveletOperation serverHistoryOp) {
versionUpdatesBuffer.add(null);
listener.onOperationReceived();
}
@Override
public void onAck(WaveletOperation serverHistoryOp, boolean isClean) {
if (isClean) {
savedStateListener.saved(channelId);
}
versionUpdatesBuffer.add(serverHistoryOp.createVersionUpdateOp(1, null));
listener.onOperationReceived();
}
};
private final Log logger;
private final GenericOperationChannel<WaveletOperation> channel;
private final String sessionId;
private final SavedStateListener savedStateListener;
private final int startVersion;
Listener listener;
public WalkaroundOperationChannel(Log logger,
SendOpService<WaveletOperation> sendService,
ReceiveOpChannel<WaveletOperation> receiveChannel,
int startVersion, String sessionId, SavedStateListener savedStateListener) {
Preconditions.checkNotNull(sendService, "Null sendService");
Preconditions.checkNotNull(receiveChannel, "Null channel");
Preconditions.checkNotNull(sessionId, "Null sessionId");
Preconditions.checkArgument(startVersion >= 0, "Invalid startVersion, %s", startVersion);
this.logger = logger;
this.startVersion = startVersion;
this.sessionId = sessionId;
this.savedStateListener = savedStateListener;
this.channel = new GenericOperationChannel<WaveletOperation>(
SchedulerInstance.getMediumPriorityTimer(), transformer,
receiveChannel, sendService, channelListener, logger);
}
@Override
public String getDebugString() {
return "Blah blah not implemented";
}
@Override
public List<HashedVersion> getReconnectVersions() {
throw new AssertionError("Not implemented");
}
@Override
public WaveletOperation peek() {
if (versionUpdatesBuffer.isEmpty()) {
return null;
}
return versionUpdatesBuffer.peek() != null
? versionUpdatesBuffer.peek()
: channel.peek();
}
@Override
public WaveletOperation receive() {
if (versionUpdatesBuffer.isEmpty()) {
return null;
}
WaveletOperation maybeOp = versionUpdatesBuffer.remove();
return maybeOp != null ? maybeOp : channel.receive();
}
@Override
public void send(WaveletOperation... operations) {
savedStateListener.unsaved(channelId);
for (WaveletOperation op : operations) {
channel.send(op);
}
}
@Override
public void setListener(Listener listener) {
Preconditions.checkNotNull(listener, "null listener");
Preconditions.checkState(this.listener == null, "Already connected");
this.listener = listener;
channel.connect(startVersion, sessionId);
}
}
| Java |
/*
* Copyright 2011 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.walkaround.wave.client.attachment;
import org.waveprotocol.wave.client.doodad.attachment.ImageThumbnail;
import org.waveprotocol.wave.client.doodad.attachment.render.ImageThumbnailWrapper;
import org.waveprotocol.wave.client.editor.EditorContext;
import org.waveprotocol.wave.client.editor.content.CMutableDocument;
import org.waveprotocol.wave.client.editor.content.ContentNode;
import org.waveprotocol.wave.client.editor.content.FocusedContentRange;
import org.waveprotocol.wave.client.wavepanel.impl.edit.EditSession;
import org.waveprotocol.wave.client.wavepanel.impl.toolbar.EditToolbar;
import org.waveprotocol.wave.model.document.util.Point;
import org.waveprotocol.wave.model.document.util.XmlStringBuilder;
/**
* A toolbar feature that pops up an upload dialog, and inserts an
* image-thumbnail doodad for the attachment that it uploads.
*
* @author hearnden@google.com (David Hearnden)
*/
public final class UploadToolbarAction implements UploadFormPopup.Listener {
/** Session from which to pull insertion location for the doodad. */
private final EditSession edit;
/** Thumbnail doodad. Created once upload starts, filled out when upload ends. */
private ImageThumbnailWrapper thumbnail;
UploadToolbarAction(EditSession edit) {
this.edit = edit;
}
/**
* Installs this feature.
*/
public static void install(final EditSession edit, EditToolbar toolbar) {
toolbar.addClickButton(Resources.css.icon(), new EditToolbar.ClickHandler() {
@Override
public void onClicked(EditorContext context) {
UploadFormPopup prompt = new UploadFormPopup();
prompt.setListener(new UploadToolbarAction(edit));
prompt.show();
}
});
}
@Override
public void onUploadStarted(String filename) {
if (!edit.isEditing()) {
// A concurrent editor may have deleted the context blip while this user
// was filling out the upload form. That was probably the cause of why
// the edit session has terminated.
// It may make sense to create a new blip somewhere and resume an edit
// session, just in order to put the thumbnail somewhere, but that logic
// would need to avoid making a bad choice of where that new blip goes
// (e.g., in an unrelated thread, or in a different private reply, etc).
// The simpler approach is to do nothing, and let the user upload the
// file again if it still makes sense (the blip in which they intended it
// to go has been deleted, so they may not want to upload it anymore).
return;
}
EditorContext context = edit.getEditor();
CMutableDocument doc = context.getDocument();
FocusedContentRange selection = context.getSelectionHelper().getSelectionPoints();
Point<ContentNode> point;
if (selection != null) {
point = selection.getFocus();
} else {
// Focus was probably lost. Bring it back.
context.focus(false);
selection = context.getSelectionHelper().getSelectionPoints();
if (selection != null) {
point = selection.getFocus();
} else {
// Still no selection. Oh well, put it at the end.
point = doc.locate(doc.size() - 1);
}
}
XmlStringBuilder content = ImageThumbnail.constructXml(null, filename);
thumbnail = ImageThumbnailWrapper.of(doc.insertXml(point, content));
}
/** Inserts an attachment thumbnail at the current edit selection. */
@Override
public void onUploadFinished(String blobId) {
if (thumbnail.getElement().isContentAttached()) {
thumbnail.setAttachmentId(blobId);
}
}
@Override
public void onUploadFailure() {
if (thumbnail != null && thumbnail.getElement().isContentAttached()) {
thumbnail.setCaptionText("Upload failed");
}
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.