code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* 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 com.google.walkaround.util.client.log.Logs.Level;
import com.google.walkaround.util.client.log.Logs.Log;
import com.google.walkaround.wave.client.rpc.AttachmentInfoService;
import org.waveprotocol.wave.client.common.util.JsoView;
import org.waveprotocol.wave.client.doodad.attachment.SimpleAttachmentManager;
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.FuzzingBackOffGenerator;
import org.waveprotocol.wave.model.util.IdentitySet;
import org.waveprotocol.wave.model.util.StringMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Queue;
/**
* Really basic RPC-based attachment manager implementation. Has some primitive
* retry logic.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class WalkaroundAttachmentManager implements SimpleAttachmentManager {
/**
* Max number of attachments to request information for at once. The server
* might also do fewer than this number at a time.
*/
// TODO(danilatos): Determine a good value for this constant and make it a flag.
private static final int MAX_INFO_REQUESTS = 200;
private final IdentitySet<Listener> listeners = CollectionUtils.createIdentitySet();
/**
* Cached attachment data. TODO(danilatos): Clear old ones if it becomes too large?
*/
private final StringMap<WalkaroundAttachment> attachments = CollectionUtils.createStringMap();
/**
* Queue of attachment ids to get information for.
*/
// TODO(danilatos): Use a set to check uniqueness with faster .contains()
private final Queue<String> infoQueue = CollectionUtils.createQueue();
private final List<String> pendingInfoIds = new ArrayList<String>();
// TODO(danilatos): Ctor arg, and flag.
private final FuzzingBackOffGenerator backoffGenerator =
new FuzzingBackOffGenerator(1500, 1800 * 1000, 0.5);
private final AttachmentInfoService service;
private final Scheduler.Task infoFetchTask = new Scheduler.Task() {
@Override public void execute() {
fetchSomeInfo();
}
};
private final AttachmentInfoService.Callback callback = new AttachmentInfoService.Callback() {
int attempts = 0;
@Override
public void onSuccess(JsoView data) {
attempts = 0;
backoffGenerator.reset();
handleInfo(data);
}
@Override
public void onFatalError(Throwable e) {
logger.log(Level.WARNING, "Attachment fatal error", e);
}
@Override
public void onConnectionError(Throwable e) {
// TODO(danilatos): Some kind of better error handling?
attempts++;
Level level = attempts > 5 ? Level.WARNING : Level.INFO;
logger.log(level, "Attachment connection error", e);
retryPendingIds(backoffGenerator.next().targetDelay);
}
};
private final Log logger;
private final TimerService scheduler;
public WalkaroundAttachmentManager(AttachmentInfoService service, Log logger) {
this(service, SchedulerInstance.getMediumPriorityTimer(), logger);
}
public WalkaroundAttachmentManager(AttachmentInfoService service, TimerService scheduler,
Log logger) {
this.service = service;
this.scheduler = scheduler;
this.logger = logger;
}
@Override
public void addListener(Listener l) {
listeners.add(l);
}
@Override
public void removeListener(Listener l) {
listeners.remove(l);
}
@Override
public Attachment getAttachment(String id) {
if (!attachments.containsKey(id)) {
attachments.put(id, new WalkaroundAttachment(id));
scheduleGetInfo(id);
}
return attachments.get(id);
}
private void scheduleGetInfo(String id) {
if (infoQueue.contains(id)) {
return;
}
infoQueue.add(id);
scheduler.schedule(infoFetchTask);
}
private void fetchSomeInfo() {
if (!pendingInfoIds.isEmpty()) {
return;
}
List<String> ids = new ArrayList<String>();
for (int i = 0; i < MAX_INFO_REQUESTS && !infoQueue.isEmpty(); i++) {
String id = infoQueue.remove();
pendingInfoIds.add(id);
}
service.fetchInfo(Collections.unmodifiableList(pendingInfoIds), callback);
}
private void handleInfo(JsoView result) {
List<String> pendingIdsCopy = new ArrayList<String>(pendingInfoIds);
final List<String> updatedIds = new ArrayList<String>();
pendingInfoIds.clear();
// TODO(danilatos) Iterate over the result instead, once random access
// to pendingInfoIds is added.
for (String id : pendingIdsCopy) {
JsoView data = (JsoView) result.getJso(id);
if (data != null) {
WalkaroundAttachment attachment = attachments.get(id);
assert attachment != null;
attachment.setData(data);
updatedIds.add(id);
} else {
pendingInfoIds.add(id);
}
}
if (!pendingInfoIds.isEmpty()) {
retryPendingIds(0);
}
// Notify listeners after doing all the important work.
listeners.each(new IdentitySet.Proc<Listener>() {
@Override public void apply(Listener l) {
for (String id : updatedIds) {
l.onThumbnailUpdated(attachments.get(id));
l.onContentUpdated(attachments.get(id));
}
}
});
}
private void retryPendingIds(int delay) {
// Put the pending ids back on the end of the queue.
for (String id : pendingInfoIds) {
infoQueue.add(id);
}
pendingInfoIds.clear();
scheduler.scheduleDelayed(infoFetchTask, delay);
}
}
| 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 com.google.gwt.user.client.Window;
import org.waveprotocol.wave.client.doodad.attachment.ImageThumbnail.ThumbnailActionHandler;
import org.waveprotocol.wave.client.doodad.attachment.render.ImageThumbnailWrapper;
/**
* @author danilatos@google.com (Daniel Danilatos)
*
*/
public class DownloadThumbnailAction implements ThumbnailActionHandler {
@Override
public boolean onClick(ImageThumbnailWrapper thumbnail) {
Window.open(thumbnail.getAttachment().getAttachmentUrl(),
thumbnail.getAttachment().getFilename(), "");
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.attachment;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.StyleInjector;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.resources.client.ImageResource;
/**
* GWT resources for the upload form.
*
* @author hearnden@google.com (David Hearnden)
*/
public final class Resources {
interface Bundle extends ClientBundle {
@Source("icon.png")
ImageResource icon();
@Source("Upload.css")
Css css();
}
interface Css extends CssResource {
String icon();
String form();
String row();
}
static final Css css = GWT.<Bundle>create(Bundle.class).css();
// Must inject everything synchronously, for popups etc.
static {
StyleInjector.inject(css.getText(), true);
}
// Utility class.
private Resources() {
}
}
| 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 com.google.walkaround.slob.shared.MessageException;
import com.google.walkaround.wave.client.JsUtil;
import org.waveprotocol.wave.client.common.util.JsoView;
import org.waveprotocol.wave.client.doodad.attachment.SimpleAttachmentManager.Attachment;
import org.waveprotocol.wave.client.doodad.attachment.SimpleAttachmentManager.UploadStatusCode;
/**
* Attachment object.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
class WalkaroundAttachment implements Attachment {
private final String id;
private UploadStatusCode status = UploadStatusCode.NOT_UPLOADING;
private JsoView data;
private ImageMetadata img = null;
private ImageMetadata thumbnail = null;
public WalkaroundAttachment(String id) {
this.id = id;
try {
setData(JsUtil.eval("{thumbnail:{width:120,height:90}}"));
} catch (MessageException e) {
throw new RuntimeException(e);
}
}
public void setStatus(UploadStatusCode status) {
this.status = status;
}
public void setData(JsoView newData) {
data = newData;
img = null;
thumbnail = null;
if (data.containsKey("image")) {
img = createImageMetadata(data.getJso("image").<JsoView>cast());
}
if (data.containsKey("thumbnail")) {
thumbnail = createImageMetadata(data.getJso("thumbnail").<JsoView>cast());
}
}
private ImageMetadata createImageMetadata(final JsoView imgData) {
return new ImageMetadata() {
@Override public int getWidth() {
return (int) imgData.getNumber("width");
}
@Override public int getHeight() {
return (int) imgData.getNumber("height");
}
};
}
@Override
public UploadStatusCode getUploadStatusCode() {
return status;
}
@Override
public String getAttachmentUrl() {
// HACK(ohler): Never return a null URL here, that would trigger bug 45.
return data.getString("url") == null ? "/brokenimage" : data.getString("url");
}
@Override
public String getCreator() {
return data.getString("creator");
}
@Override
public String getFilename() {
return data.getString("filename");
}
@Override
public String getMimeType() {
return data.getString("mimeType");
}
@Override
public Long getSize() {
// TODO(danilatos) Fix the waveprotocol interface to be long not Long.
return data.containsKey("size") ? (long) data.getNumber("size") : null;
}
@Override
public boolean isMalware() {
return data.containsKey("isMalware") ? data.getBoolean("isMalware") : false;
}
@Override
public String getAttachmentId() {
return id;
}
@Override
public ImageMetadata getContentImageMetadata() {
return img;
}
@Override
public ImageMetadata getThumbnailImageMetadata() {
return thumbnail;
}
@Override
public String getThumbnailUrl() {
return data.getString("thumbnailUrl");
}
////
// hacks
@Override
public double getUploadStatusProgress() {
return 0.2;
}
@Override
public long getUploadedByteCount() {
return 0;
}
////
@Override
public String getStatus() {
throw new AssertionError("Not implemented");
}
@Override
public long getUploadRetryCount() {
throw new AssertionError("Not implemented");
}
@Override
public Thumbnail getThumbnail() {
throw new AssertionError("Not implemented");
}
@Override
public Image getImage() {
throw new AssertionError("Not implemented");
}
}
| 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 com.google.common.base.Preconditions;
import com.google.gwt.core.client.Duration;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.IFrameElement;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
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.Event;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.SubmitButton;
import com.google.gwt.user.client.ui.UIObject;
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.DomHelper;
import org.waveprotocol.wave.client.common.util.DomHelper.HandlerReference;
import org.waveprotocol.wave.client.common.util.DomHelper.JavaScriptEventListener;
import org.waveprotocol.wave.client.widget.popup.CenterPopupPositioner;
import org.waveprotocol.wave.client.widget.popup.PopupChrome;
import org.waveprotocol.wave.client.widget.popup.PopupChromeFactory;
import org.waveprotocol.wave.client.widget.popup.PopupFactory;
import org.waveprotocol.wave.client.widget.popup.UniversalPopup;
/**
* Manages the flow for uploading attachments.
* <p>
* First, a popup is shown with a form containing the file input. In parallel, a
* hidden iframe is injected to the body. The form's target is set to that
* iframe, so it can be submitted without reloading the main frame.
* Additionally, that iframe is used to fetch an upload token, encoded as the
* action URL for the form (an AppEngine requirement). An iframe is used for
* fetching the token instead of an XHR only because the iframe is already
* needed for the form submission.
* <p>
* On retrieval of the upload token, the popup form's action URL is set, and its
* submit button is enabled.
*
* @author hearnden@google.com (David Hearnden)
*/
public final class UploadFormPopup {
/** Observer of the upload flow. */
public interface Listener {
/** Notifies this listener that the file is about to start uploading.
* @param filename */
void onUploadStarted(String filename);
/** Notifies this listener that the file has been uploaded. */
void onUploadFinished(String blobId);
/** Notifies this listener that an error occured. */
void onUploadFailure();
}
interface Binder extends UiBinder<FormPanel, UploadFormPopup> {
}
private static final Binder BINDER = GWT.create(Binder.class);
@UiField(provided = true)
static final Resources.Css css = Resources.css;
private static final Log log = Logs.create("upload");
/** Counter for ensuring unique names for the iframes. */
private static int iframeId;
// The popup.
private final UniversalPopup popup;
private final FormPanel form;
@UiField
FileUpload file;
@UiField
SubmitButton submit;
private final IFrameElement iframe;
private final HandlerReference onloadRegistration;
/** Optional listener. */
private Listener listener;
/** States in the upload flow. */
enum Stage {
START, FETCHING_TOKEN, HAVE_TOKEN, UPLOADING_FILE, END
}
/** Flow state. Increases monotonically, never null. */
private Stage stage = Stage.START;
/**
* Creates an upload popup.
*/
public UploadFormPopup() {
form = BINDER.createAndBindUi(this);
PopupChrome chrome = PopupChromeFactory.createPopupChrome();
chrome.enableTitleBar();
popup = PopupFactory.createPopup(null, new CenterPopupPositioner(), chrome, false);
popup.getTitleBar().setTitleText("Upload attachment");
popup.add(form);
iframe = Document.get().createIFrameElement();
iframe.setName("_uploadform" + iframeId++);
// HACK(danilatos): Prevent browser from caching due to whatever reason
iframe.setSrc("/uploadform?nocache=" + Duration.currentTimeMillis());
form.getElement().setAttribute("target", iframe.getName());
onloadRegistration =
DomHelper.registerEventHandler(iframe, "load", new JavaScriptEventListener() {
@Override
public void onJavaScriptEvent(String name, Event event) {
onIframeLoad();
}
});
UIObject.setVisible(iframe, false);
}
/** Sets the listener for upload status events. */
public void setListener(Listener listener) {
Preconditions.checkState(this.listener == null);
Preconditions.checkArgument(listener != null);
this.listener = listener;
}
/** Transitions into the end state, releasing resources. */
private void destroy() {
onloadRegistration.unregister();
popup.hide();
iframe.removeFromParent();
stage = Stage.END;
log.log(Level.INFO, "end");
}
/** Transitions into the end state due to a failure. */
private void fail(String msg) {
log.log(Level.WARNING, "Upload failed. ", msg);
destroy();
if (listener != null) {
listener.onUploadFailure();
}
}
/** Shows the popup, initiating the upload flow. */
public void show() {
Preconditions.checkState(stage == Stage.START);
stage = Stage.FETCHING_TOKEN;
popup.show();
Document.get().getBody().appendChild(iframe);
log.log(Level.INFO, "flow started");
}
private void onIframeLoad() {
switch (stage) {
case FETCHING_TOKEN:
String action = getTokenedAction();
if (action == null) {
fail("could not get upload token.");
} else {
form.setAction(action);
maybeEnableSubmit();
stage = Stage.HAVE_TOKEN;
log.log(Level.INFO, "token received: ", action);
}
break;
case UPLOADING_FILE:
String attachmentId = getAttachmentId();
if (attachmentId == null) {
fail("upload failed.");
} else {
destroy();
log.log(Level.INFO, "success: ", attachmentId);
if (listener != null) {
listener.onUploadFinished(attachmentId);
}
}
break;
case END:
// Some failure has already ended the flow. Ignore.
break;
default:
throw new AssertionError();
}
}
/**
* Enables the submit button if this form has an upload token and a file is
* selected. Otherwise, disables it.
*/
private void maybeEnableSubmit() {
submit.setEnabled(stage == Stage.HAVE_TOKEN && file.getFilename() != null);
}
//
// Form events
//
@UiHandler("file")
void handleFile(ChangeEvent e) {
maybeEnableSubmit();
}
@UiHandler("cancel")
void handleCancel(ClickEvent e) {
destroy();
stage = Stage.END;
log.log(Level.INFO, "cancelled");
}
@UiHandler("submit")
void handleSubmit(ClickEvent e) {
Preconditions.checkState(stage == Stage.HAVE_TOKEN);
// The browser's default action can not be relied upon to submit the form,
// because this handler is removing the form from the DOM, so a manual
// submit is required (before hiding the popup).
e.stopPropagation();
form.submit();
popup.hide();
stage = Stage.UPLOADING_FILE;
log.log(Level.INFO, "posting file");
if (listener != null) {
listener.onUploadStarted(fixFilename(file.getFilename()));
}
}
/**
* Gets a property of the iframe's window. Setting such properties is how the
* iframe communicates back with this window.
*/
private static native String getFrameProperty(IFrameElement frame, String property)
/*-{
return frame.contentWindow[property];
}-*/;
private String getTokenedAction() {
return getFrameProperty(iframe, "_formAction");
}
private String getAttachmentId() {
return getFrameProperty(iframe, "_attachmentId");
}
/** Strips the C:\fakepath\ prefix inserted by some browsers. */
private static String fixFilename(String filename) {
// Some browsers (e.g., Chrome) report filenames "foo.png" with a fake path:
// "C:\fakepath\foo.png". Other browsers (e.g., Firefox) report filenames
// properly: "foo.png".
String fakepath = "C:\\fakepath\\";
return filename.startsWith(fakepath) ? filename.substring(fakepath.length()) : filename;
}
}
| 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 org.waveprotocol.wave.client.account.Profile;
import org.waveprotocol.wave.client.account.ProfileManager;
import org.waveprotocol.wave.client.common.safehtml.EscapeUtils;
import org.waveprotocol.wave.client.common.safehtml.SafeHtmlBuilder;
import org.waveprotocol.wave.client.render.RenderingRules;
import org.waveprotocol.wave.client.state.ThreadReadStateMonitor;
import org.waveprotocol.wave.client.uibuilder.HtmlClosure;
import org.waveprotocol.wave.client.uibuilder.HtmlClosureCollection;
import org.waveprotocol.wave.client.uibuilder.UiBuilder;
import org.waveprotocol.wave.client.wavepanel.render.ShallowBlipRenderer;
import org.waveprotocol.wave.client.wavepanel.view.ViewIdMapper;
import org.waveprotocol.wave.client.wavepanel.view.dom.full.AnchorViewBuilder;
import org.waveprotocol.wave.client.wavepanel.view.dom.full.BlipMetaViewBuilder;
import org.waveprotocol.wave.client.wavepanel.view.dom.full.BlipViewBuilder;
import org.waveprotocol.wave.client.wavepanel.view.dom.full.ContinuationIndicatorViewBuilder;
import org.waveprotocol.wave.client.wavepanel.view.dom.full.InlineThreadViewBuilder;
import org.waveprotocol.wave.client.wavepanel.view.dom.full.ParticipantNameViewBuilder;
import org.waveprotocol.wave.client.wavepanel.view.dom.full.ParticipantsViewBuilder;
import org.waveprotocol.wave.client.wavepanel.view.dom.full.ReplyBoxViewBuilder;
import org.waveprotocol.wave.client.wavepanel.view.dom.full.RootThreadViewBuilder;
import org.waveprotocol.wave.client.wavepanel.view.dom.full.ViewFactory;
import org.waveprotocol.wave.model.conversation.Conversation;
import org.waveprotocol.wave.model.conversation.ConversationBlip;
import org.waveprotocol.wave.model.conversation.ConversationThread;
import org.waveprotocol.wave.model.conversation.ConversationView;
import org.waveprotocol.wave.model.util.CollectionUtils;
import org.waveprotocol.wave.model.util.IdentityMap;
import org.waveprotocol.wave.model.util.IdentityMap.ProcV;
import org.waveprotocol.wave.model.util.IdentityMap.Reduce;
import org.waveprotocol.wave.model.util.StringMap;
import org.waveprotocol.wave.model.wave.ParticipantId;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* HACK(ohler): copy of
* https://svn.apache.org/repos/asf/incubator/wave/trunk/src/org/waveprotocol/wave/client/wavepanel/render/FullDomRenderer.java
* since that's final and we want to override the participant rendering.
* TODO(ohler): Change the wavepanel code to allow more direct customization of
* how participants are rendered.
*/
public class MyFullDomRenderer implements RenderingRules<UiBuilder> {
public interface DocRefRenderer {
UiBuilder render(ConversationBlip blip,
IdentityMap<ConversationThread, UiBuilder> replies);
DocRefRenderer EMPTY = new DocRefRenderer() {
@Override
public UiBuilder render(ConversationBlip blip,
IdentityMap<ConversationThread, UiBuilder> replies) {
return UiBuilder.Constant.of(EscapeUtils.fromSafeConstant("<div></div>"));
}
};
}
public interface ParticipantsRenderer {
UiBuilder render(Conversation c);
ParticipantsRenderer EMPTY = new ParticipantsRenderer() {
@Override
public UiBuilder render(Conversation c) {
return UiBuilder.Constant.of(EscapeUtils.fromSafeConstant("<div></div>"));
}
};
}
private final ShallowBlipRenderer blipPopulator;
private final DocRefRenderer docRenderer;
private final ViewIdMapper viewIdMapper;
private final ViewFactory viewFactory;
private final ProfileManager profileManager;
private final ThreadReadStateMonitor readMonitor;
public MyFullDomRenderer(ShallowBlipRenderer blipPopulator, DocRefRenderer docRenderer,
ProfileManager profileManager, ViewIdMapper viewIdMapper, ViewFactory viewFactory,
ThreadReadStateMonitor readMonitor) {
this.blipPopulator = blipPopulator;
this.docRenderer = docRenderer;
this.profileManager = profileManager;
this.viewIdMapper = viewIdMapper;
this.viewFactory = viewFactory;
this.readMonitor = readMonitor;
}
@Override
public UiBuilder render(ConversationView wave,
IdentityMap<Conversation, UiBuilder> conversations) {
// return the first conversation in the view.
// TODO(hearnden): select the 'best' conversation.
return conversations.isEmpty() ? null : getFirstConversation(conversations);
}
public UiBuilder getFirstConversation(IdentityMap<Conversation, UiBuilder> conversations) {
return conversations.reduce(null, new Reduce<Conversation, UiBuilder, UiBuilder>() {
@Override
public UiBuilder apply(UiBuilder soFar, Conversation key, UiBuilder item) {
// Pick the first rendering (any will do).
return soFar == null ? item : soFar;
}
});
}
@Override
public UiBuilder render(Conversation conversation, UiBuilder participantsUi, UiBuilder threadUi) {
String id = viewIdMapper.conversationOf(conversation);
boolean isTop = !conversation.hasAnchor();
return isTop ? viewFactory.createTopConversationView(id, threadUi, participantsUi)
: viewFactory.createInlineConversationView(id, threadUi, participantsUi);
}
@Override
public UiBuilder render(Conversation conversation, StringMap<UiBuilder> participantUis) {
HtmlClosureCollection participantsUi = new HtmlClosureCollection();
for (ParticipantId participant : conversation.getParticipantIds()) {
participantsUi.add(participantUis.get(participant.getAddress()));
}
String id = viewIdMapper.participantsOf(conversation);
return ParticipantsViewBuilder.create(id, participantsUi);
}
@Override
public UiBuilder render(Conversation conversation, ParticipantId participant) {
Profile profile = profileManager.getProfile(participant);
String id = viewIdMapper.participantOf(conversation, participant);
// Use ParticipantAvatarViewBuilder for avatars.
ParticipantNameViewBuilder participantUi = ParticipantNameViewBuilder.create(id);
participantUi.setAvatar(profile.getImageUrl());
participantUi.setName(profile.getFullName());
return participantUi;
}
@Override
public UiBuilder render(final ConversationThread thread,
final IdentityMap<ConversationBlip, UiBuilder> blipUis) {
HtmlClosure blipsUi = new HtmlClosure() {
@Override
public void outputHtml(SafeHtmlBuilder out) {
for (ConversationBlip blip : thread.getBlips()) {
UiBuilder blipUi = blipUis.get(blip);
// Not all blips are rendered.
if (blipUi != null) {
blipUi.outputHtml(out);
}
}
}
};
String threadId = viewIdMapper.threadOf(thread);
String replyIndicatorId = viewIdMapper.replyIndicatorOf(thread);
UiBuilder builder = null;
if (thread.getConversation().getRootThread() == thread) {
ReplyBoxViewBuilder replyBoxBuilder =
ReplyBoxViewBuilder.create(replyIndicatorId);
builder = RootThreadViewBuilder.create(threadId, blipsUi, replyBoxBuilder);
} else {
ContinuationIndicatorViewBuilder indicatorBuilder = ContinuationIndicatorViewBuilder.create(
replyIndicatorId);
InlineThreadViewBuilder inlineBuilder =
InlineThreadViewBuilder.create(threadId, blipsUi, indicatorBuilder);
int read = readMonitor.getReadCount(thread);
int unread = readMonitor.getUnreadCount(thread);
inlineBuilder.setTotalBlipCount(read + unread);
inlineBuilder.setUnreadBlipCount(unread);
builder = inlineBuilder;
}
return builder;
}
@Override
public UiBuilder render(final ConversationBlip blip, UiBuilder document,
final IdentityMap<ConversationThread, UiBuilder> anchorUis,
final IdentityMap<Conversation, UiBuilder> nestedConversations) {
UiBuilder threadsUi = new UiBuilder() {
@Override
public void outputHtml(SafeHtmlBuilder out) {
for (ConversationThread thread : blip.getReplyThreads()) {
anchorUis.get(thread).outputHtml(out);
}
}
};
UiBuilder convsUi = new UiBuilder() {
@Override
public void outputHtml(SafeHtmlBuilder out) {
// Order by conversation id. Ideally, the sort key would be creation
// time, but that is not exposed in the conversation API.
final List<Conversation> ordered = CollectionUtils.newArrayList();
nestedConversations.each(new ProcV<Conversation, UiBuilder>() {
@Override
public void apply(Conversation conv, UiBuilder ui) {
ordered.add(conv);
}
});
Collections.sort(ordered, new Comparator<Conversation>() {
@Override
public int compare(Conversation o1, Conversation o2) {
return o1.getId().compareTo(o2.getId());
}
});
List<UiBuilder> orderedUis = CollectionUtils.newArrayList();
for (Conversation conv : ordered) {
nestedConversations.get(conv).outputHtml(out);
}
}
};
BlipMetaViewBuilder metaUi = BlipMetaViewBuilder.create(viewIdMapper.metaOf(blip), document);
blipPopulator.render(blip, metaUi);
return BlipViewBuilder.create(viewIdMapper.blipOf(blip), metaUi, threadsUi, convsUi);
}
/**
*/
@Override
public UiBuilder render(
ConversationBlip blip, IdentityMap<ConversationThread, UiBuilder> replies) {
return docRenderer.render(blip, replies);
}
@Override
public UiBuilder render(ConversationThread thread, UiBuilder threadR) {
String id = EscapeUtils.htmlEscape(viewIdMapper.defaultAnchorOf(thread));
return AnchorViewBuilder.create(id, threadR);
}
}
| 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.dom.client.Element;
import com.google.gwt.user.client.Window;
import com.google.walkaround.wave.client.WalkaroundOperationChannel.SavedStateListener;
import com.google.walkaround.wave.client.rpc.Rpc.ConnectionState;
import com.google.walkaround.wave.client.rpc.Rpc.ConnectionStateListener;
import org.waveprotocol.wave.client.common.safehtml.EscapeUtils;
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.StringSet;
/**
* Simple saved state indicator.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
// TODO(danilatos): Make the UI pretty
public class SavedStateIndicator implements SavedStateListener, ConnectionStateListener {
private enum SavedState {
SAVED("Saved"),
UNSAVED("Unsaved..."),
TURBULENCE("Unable to save");
final String message;
private SavedState(String message) {
this.message = message;
}
}
private static final int UPDATE_DELAY_MS = 300;
private final Scheduler.Task updateTask = new Scheduler.Task() {
@Override public void execute() {
updateDisplay();
}
};
private final Element element;
private final TimerService scheduler;
private final StringSet channels = CollectionUtils.createStringSet();
private boolean turbulenced = false;
private ConnectionState connectionState = ConnectionState.CONNECTED;
private SavedState visibleSavedState = SavedState.SAVED;
public SavedStateIndicator(Element element) {
this.element = element;
this.scheduler = SchedulerInstance.getLowPriorityTimer();
}
@Override
public void saved(String channelId) {
Preconditions.checkState(channels.contains(channelId), "Already saved channel %s", channelId);
channels.remove(channelId);
maybeUpdateDisplay();
}
@Override
public void unsaved(String channelId) {
channels.add(channelId);
maybeUpdateDisplay();
}
@Override
public void turbulenced() {
turbulenced = true;
maybeUpdateDisplay();
}
@Override
public void connectionStateChanged(ConnectionState newConnectionState) {
this.connectionState = newConnectionState;
updateDisplay();
}
private void maybeUpdateDisplay() {
if (needsUpdating()) {
switch (currentSavedState()) {
case SAVED:
scheduler.scheduleDelayed(updateTask, UPDATE_DELAY_MS);
break;
case TURBULENCE:
case UNSAVED:
updateDisplay();
break;
default:
throw new AssertionError("unknown " + currentSavedState());
}
} else {
scheduler.cancel(updateTask);
}
}
private boolean needsUpdating() {
return visibleSavedState != currentSavedState();
}
private SavedState currentSavedState() {
return turbulenced ? SavedState.TURBULENCE
: channels.isEmpty() ? SavedState.SAVED : SavedState.UNSAVED;
}
private void updateDisplay() {
visibleSavedState = currentSavedState();
element.setInnerHTML(visibleSavedState.message + htmlForConnectionState());
}
private String htmlForConnectionState() {
switch (connectionState) {
case CONNECTED: return "";
case LOGGED_OUT: {
String self = Window.Location.getHref();
return "<div>You are logged out. <a href=\"" + EscapeUtils.htmlEscape(self)
+ "\">Reload</a> " + " the page to log in again</div>";
}
case OFFLINE: return "<div>You are not connected</div>";
case SOFT_RELOAD:
case HARD_RELOAD: {
// TODO(danilatos): Refresh automatically (perhaps not here) if there are no
// unsaved changes.
String self = Window.Location.getHref();
return "<div>Please <a href=\"" + EscapeUtils.htmlEscape(self) + "\">reload</a> "
+ " the page to recover</div>";
}
default:
throw new AssertionError("unknown " + connectionState);
}
}
}
| 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.util.client.log.Logs;
import com.google.walkaround.util.client.log.Logs.Level;
import com.google.walkaround.util.client.log.Logs.Log;
/**
* Dumps read state commands to the debug log.
*
* @author hearnden@google.com (David Hearnden)
*/
public final class FakeReadStateService implements ReadStateService {
private static final Log LOG = Logs.create("readstate");
FakeReadStateService() {
}
public static FakeReadStateService create() {
return new FakeReadStateService();
}
@Override
public void setReadState(boolean read) {
LOG.log(Level.INFO, "Marking wave as ", read ? "read" : "unread");
}
}
| 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.core.client.JavaScriptException;
import com.google.walkaround.slob.shared.MessageException;
import org.waveprotocol.wave.client.common.util.JsoView;
/**
* Application-independent GWT utilities.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class JsUtil {
public static JsoView eval(String data) throws MessageException {
// TODO(danilatos): Use JSON.parse() instead of surrounding with parens
// in browsers that support it.
if (!data.startsWith("(")) {
data = "(" + data + ")";
}
try {
return evalNative(data);
} catch (JavaScriptException e) {
throw new MessageException(e);
}
}
static native JsoView evalNative(String data) throws JavaScriptException /*-{
return eval(data);
}-*/;
}
| 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 org.waveprotocol.wave.client.state.BlipReadStateMonitor;
/**
* Forwards a wave's read state into a {@link ReadStateService}.
*
* @author hearnden@google.com (David Hearnden)
*/
public final class ReadStateSynchronizer implements BlipReadStateMonitor.Listener {
private final ReadStateService target;
private final BlipReadStateMonitor mon;
/** The last state written. */
private boolean wasRead;
ReadStateSynchronizer(ReadStateService target, BlipReadStateMonitor mon) {
this.target = target;
this.mon = mon;
}
/** Creates a synchronizer, and starts pushing changes. */
public static ReadStateSynchronizer create(ReadStateService target,
BlipReadStateMonitor mon) {
ReadStateSynchronizer synchronizer = new ReadStateSynchronizer(target, mon);
synchronizer.init();
return synchronizer;
}
private void init() {
write(mon.getUnreadCount() == 0);
mon.addListener(this);
}
/** Destroys this synchronizer, releasing its resources. */
public void destroy() {
mon.removeListener(this);
}
/** Writes the current read state. */
private void write(boolean read) {
target.setReadState(read);
this.wasRead = read;
}
@Override
public void onReadStateChanged() {
boolean read = (mon.getUnreadCount() == 0);
if (this.wasRead != read) {
write(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.proto.Delta;
import com.google.walkaround.proto.OperationBatch;
import com.google.walkaround.proto.ProtocolWaveletOperation;
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.OperationBatchJsoImpl;
import com.google.walkaround.proto.jso.ProtocolWaveletOperationJsoImpl;
import com.google.walkaround.proto.jso.WalkaroundWaveletSnapshotJsoImpl;
import com.google.walkaround.proto.jso.WaveletDiffSnapshotJsoImpl;
import com.google.walkaround.slob.shared.MessageException;
import com.google.walkaround.wave.shared.MessageFactoryHelper;
import com.google.walkaround.wave.shared.MessageSerializer;
/**
* ClientWaveSerializer is capable of both serializing and deserializing
* Wavelets and Deltas to and from JSON in client environment.
*
* @author piotrkaleta@google.com (Piotr Kaleta)
*/
public class ClientMessageSerializer implements MessageSerializer {
public ClientMessageSerializer() {
if (MessageFactoryHelper.getFactory() == null) {
MessageFactoryHelper.setFactory(new MessageFactoryClient());
} else {
Preconditions.checkState(MessageFactoryHelper.getFactory() instanceof MessageFactoryClient);
}
}
@Override
public String serializeOp(ProtocolWaveletOperation waveletOp) {
return ((ProtocolWaveletOperationJsoImpl) waveletOp).toJson();
}
@Override
public ProtocolWaveletOperationJsoImpl deserializeOp(String serializedDelta)
throws MessageException {
return JsUtil.eval(serializedDelta).cast();
}
@Override
public String serializeWavelet(WalkaroundWaveletSnapshot waveletSnapshot) {
return ((WalkaroundWaveletSnapshotJsoImpl) waveletSnapshot).toJson();
}
@Override
public WalkaroundWaveletSnapshotJsoImpl deserializeWavelet(String serializedSnapshot)
throws MessageException {
return JsUtil.eval(serializedSnapshot).cast();
}
@Override
public String serializeDiff(WaveletDiffSnapshot diff) {
return ((WaveletDiffSnapshotJsoImpl) diff).toJson();
}
@Override
public WaveletDiffSnapshotJsoImpl deserializeDiff(String input) throws MessageException {
return JsUtil.eval(input).cast();
}
@Override
public String serializeOperationBatch(OperationBatch operationBatch) {
return ((OperationBatchJsoImpl) operationBatch).toJson();
}
@Override
public OperationBatchJsoImpl deserializeOperationBatch(String input) throws MessageException {
return JsUtil.eval(input).cast();
}
@Override
public String serializeDelta(Delta input) {
return ((DeltaJsoImpl) input).toJson();
}
@Override
public DeltaJsoImpl deserializeDelta(String input) throws MessageException {
return JsUtil.eval(input).cast();
}
}
| 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.common.collect.Iterables;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT.UncaughtExceptionHandler;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.UIObject;
import com.google.walkaround.proto.ClientVars.LiveClientVars;
import com.google.walkaround.proto.ClientVars.StaticClientVars;
import com.google.walkaround.proto.ClientVars.UdwLoadData;
import com.google.walkaround.proto.ConnectResponse;
import com.google.walkaround.proto.WalkaroundWaveletSnapshot;
import com.google.walkaround.proto.WaveletDiffSnapshot;
import com.google.walkaround.proto.jso.ClientVarsJsoImpl;
import com.google.walkaround.proto.jso.DeltaJsoImpl;
import com.google.walkaround.slob.client.GenericOperationChannel.ReceiveOpChannel;
import com.google.walkaround.slob.client.GenericOperationChannel.SendOpService;
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.ErrorReportingLogHandler;
import com.google.walkaround.util.client.log.LogPanel;
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.util.shared.Assert;
import com.google.walkaround.util.shared.RandomBase64Generator;
import com.google.walkaround.util.shared.RandomBase64Generator.RandomProvider;
import com.google.walkaround.wave.client.MyFullDomRenderer.DocRefRenderer;
import com.google.walkaround.wave.client.attachment.DownloadThumbnailAction;
import com.google.walkaround.wave.client.attachment.UploadToolbarAction;
import com.google.walkaround.wave.client.attachment.WalkaroundAttachmentManager;
import com.google.walkaround.wave.client.profile.ContactsManager;
import com.google.walkaround.wave.client.rpc.AjaxRpc;
import com.google.walkaround.wave.client.rpc.AttachmentInfoService;
import com.google.walkaround.wave.client.rpc.ChannelConnectService;
import com.google.walkaround.wave.client.rpc.LoadWaveService;
import com.google.walkaround.wave.client.rpc.LoadWaveService.ConnectCallback;
import com.google.walkaround.wave.client.rpc.SubmitDeltaService;
import com.google.walkaround.wave.client.rpc.WaveletMap;
import com.google.walkaround.wave.client.rpc.WaveletMap.WaveletEntry;
import com.google.walkaround.wave.shared.IdHack;
import com.google.walkaround.wave.shared.Versions;
import com.google.walkaround.wave.shared.WaveSerializer;
import org.waveprotocol.wave.client.StageOne;
import org.waveprotocol.wave.client.StageThree;
import org.waveprotocol.wave.client.StageTwo;
import org.waveprotocol.wave.client.StageZero;
import org.waveprotocol.wave.client.Stages;
import org.waveprotocol.wave.client.account.Profile;
import org.waveprotocol.wave.client.account.ProfileManager;
import org.waveprotocol.wave.client.common.util.AsyncHolder;
import org.waveprotocol.wave.client.common.util.JsoView;
import org.waveprotocol.wave.client.concurrencycontrol.MuxConnector;
import org.waveprotocol.wave.client.concurrencycontrol.StaticChannelBinder;
import org.waveprotocol.wave.client.concurrencycontrol.WaveletOperationalizer;
import org.waveprotocol.wave.client.doodad.DoodadInstallers.ConversationInstaller;
import org.waveprotocol.wave.client.doodad.attachment.ImageThumbnail;
import org.waveprotocol.wave.client.editor.content.Registries;
import org.waveprotocol.wave.client.render.ReductionBasedRenderer;
import org.waveprotocol.wave.client.render.RenderingRules;
import org.waveprotocol.wave.client.scheduler.Scheduler.Task;
import org.waveprotocol.wave.client.scheduler.SchedulerInstance;
import org.waveprotocol.wave.client.uibuilder.UiBuilder;
import org.waveprotocol.wave.client.wave.LazyContentDocument;
import org.waveprotocol.wave.client.wave.RegistriesHolder;
import org.waveprotocol.wave.client.wave.SimpleDiffDoc;
import org.waveprotocol.wave.client.wave.WaveDocuments;
import org.waveprotocol.wave.client.wavepanel.render.DocumentRegistries.Builder;
import org.waveprotocol.wave.client.wavepanel.render.HtmlDomRenderer;
import org.waveprotocol.wave.client.wavepanel.view.BlipView;
import org.waveprotocol.wave.client.wavepanel.view.ParticipantView;
import org.waveprotocol.wave.client.wavepanel.view.dom.FullStructure;
import org.waveprotocol.wave.client.wavepanel.view.dom.ModelAsViewProvider;
import org.waveprotocol.wave.client.wavepanel.view.dom.ParticipantAvatarDomImpl;
import org.waveprotocol.wave.client.wavepanel.view.dom.UpgradeableDomAsViewProvider;
import org.waveprotocol.wave.client.wavepanel.view.dom.full.BlipQueueRenderer;
import org.waveprotocol.wave.client.wavepanel.view.dom.full.DomRenderer;
import org.waveprotocol.wave.client.wavepanel.view.dom.full.ParticipantAvatarViewBuilder;
import org.waveprotocol.wave.client.wavepanel.view.impl.ParticipantViewImpl;
import org.waveprotocol.wave.client.widget.popup.AlignedPopupPositioner;
import org.waveprotocol.wave.client.widget.profile.ProfilePopupView;
import org.waveprotocol.wave.client.widget.profile.ProfilePopupWidget;
import org.waveprotocol.wave.concurrencycontrol.channel.WaveViewService;
import org.waveprotocol.wave.model.conversation.Conversation;
import org.waveprotocol.wave.model.conversation.ConversationBlip;
import org.waveprotocol.wave.model.conversation.ConversationThread;
import org.waveprotocol.wave.model.document.indexed.IndexedDocumentImpl;
import org.waveprotocol.wave.model.document.operation.DocInitialization;
import org.waveprotocol.wave.model.document.operation.DocOp;
import org.waveprotocol.wave.model.id.IdGenerator;
import org.waveprotocol.wave.model.id.ModernIdSerialiser;
import org.waveprotocol.wave.model.id.WaveletId;
import org.waveprotocol.wave.model.operation.wave.WaveletOperation;
import org.waveprotocol.wave.model.schema.SchemaProvider;
import org.waveprotocol.wave.model.schema.conversation.ConversationSchemas;
import org.waveprotocol.wave.model.testing.RandomProviderImpl;
import org.waveprotocol.wave.model.util.CollectionUtils;
import org.waveprotocol.wave.model.util.IdentityMap;
import org.waveprotocol.wave.model.util.StringMap;
import org.waveprotocol.wave.model.wave.InvalidParticipantAddress;
import org.waveprotocol.wave.model.wave.ParticipantId;
import org.waveprotocol.wave.model.wave.Wavelet;
import org.waveprotocol.wave.model.wave.data.DocumentFactory;
import org.waveprotocol.wave.model.wave.data.ObservableWaveletData;
import org.waveprotocol.wave.model.wave.data.WaveViewData;
import org.waveprotocol.wave.model.wave.data.impl.ObservablePluggableMutableDocument;
import org.waveprotocol.wave.model.wave.data.impl.WaveViewDataImpl;
import org.waveprotocol.wave.model.wave.data.impl.WaveletDataImpl;
import javax.annotation.Nullable;
/**
* Walkaround configuration for Undercurrent client
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class Walkaround implements EntryPoint {
// TODO(danilatos): Enable this once Undercurrent does not crash. Or, delete if undercurrent
// ends up doing it by default:
//
// static {
// CollectionUtils.setDefaultCollectionFactory(new JsoCollectionFactory());
// }
static final Log logger = Logs.create("client");
private static final String WAVEPANEL_PLACEHOLDER = "initialHtml";
// TODO(danilatos): flag
private static final int VERSION_CHECK_INTERVAL_MS = 15 * 1000;
private static final String OOPHM_SUFFIX = "&gwt.codesvr=127.0.0.1:9997";
private final ClientVarsJsoImpl clientVars = nativeGetVars().cast();
private final WaveSerializer serializer = new WaveSerializer(new ClientMessageSerializer());
private final WaveletMap wavelets = new WaveletMap();
private SlobId convObjectId;
private SlobId udwObjectId;
private IdGenerator idGenerator;
private static native JsoView nativeGetVars() /*-{
return $wnd.__vars;
}-*/;
private static LogPanel domLogger;
private static boolean loaded;
private WaveletEntry makeEntry(SlobId objectId,
@Nullable ConnectResponse connectResponse, WaveletDataImpl wavelet) {
if (connectResponse != null) {
Preconditions.checkArgument(
objectId.getId().equals(connectResponse.getSignedSession().getSession().getObjectId()),
"Mismatched object ids: %s, %s", objectId, connectResponse);
}
return new WaveletEntry(objectId,
connectResponse == null ? null : connectResponse.getSignedSessionString(),
connectResponse == null ? null : connectResponse.getSignedSession().getSession(),
connectResponse == null ? null : connectResponse.getChannelToken(),
wavelet);
}
private WaveletEntry parseConvWaveletData(
@Nullable ConnectResponse connectResponse, WaveletDiffSnapshot diffSnapshot,
DocumentFactory<?> docFactory, StringMap<DocOp> diffMap) {
WaveSerializer waveSerializer = new WaveSerializer(new ClientMessageSerializer(), docFactory);
WaveletDataImpl wavelet;
try {
StringMap<DocOp> diffOps = waveSerializer.deserializeDocumentsDiffs(diffSnapshot);
diffMap.putAll(diffOps);
wavelet = waveSerializer.createWaveletData(
IdHack.convWaveletNameFromConvObjectId(convObjectId), diffSnapshot);
} catch (MessageException e) {
throw new RuntimeException(e);
}
return makeEntry(convObjectId, connectResponse, wavelet);
}
private WaveletEntry parseUdwData(
@Nullable ConnectResponse connectResponse, WalkaroundWaveletSnapshot snapshot,
DocumentFactory<?> docFactory) {
WaveSerializer serializer = new WaveSerializer(new ClientMessageSerializer(), docFactory);
WaveletDataImpl wavelet;
try {
wavelet = serializer.createWaveletData(
IdHack.udwWaveletNameFromConvObjectIdAndUdwObjectId(convObjectId, udwObjectId),
snapshot);
} catch (MessageException e) {
throw new RuntimeException(e);
}
return makeEntry(udwObjectId, connectResponse, wavelet);
}
/**
* Runs the harness script.
*/
@Override
public void onModuleLoad() {
if (loaded) {
return;
}
loaded = true;
setupLogging();
setupShell();
// Bail early if the server sent us an error message
if (clientVars.hasErrorVars()) {
Element placeHolder = Document.get().getElementById(WAVEPANEL_PLACEHOLDER);
String errorMessage = "Error: " + clientVars.getErrorVars().getErrorMessage();
if (placeHolder != null) {
placeHolder.setInnerText(errorMessage);
} else {
Window.alert(errorMessage);
}
return;
}
logger.log(Level.INFO, "Init");
final SavedStateIndicator indicator = new SavedStateIndicator(
Document.get().getElementById("savedStateContainer"));
final AjaxRpc rpc = new AjaxRpc("", indicator);
final boolean isLive;
final boolean useUdw;
@Nullable final UdwLoadData udwData;
final int randomSeed;
final String userIdString;
final boolean haveOAuthToken;
final String convObjectIdString;
final WaveletDiffSnapshot convSnapshot;
@Nullable final ConnectResponse convConnectResponse;
if (clientVars.hasStaticClientVars()) {
isLive = false;
StaticClientVars vars = clientVars.getStaticClientVars();
randomSeed = vars.getRandomSeed();
userIdString = vars.getUserEmail();
haveOAuthToken = vars.getHaveOauthToken();
convObjectIdString = vars.getConvObjectId();
convSnapshot = vars.getConvSnapshot();
convConnectResponse = null;
useUdw = false;
udwData = null;
} else {
isLive = true;
LiveClientVars vars = clientVars.getLiveClientVars();
randomSeed = vars.getRandomSeed();
userIdString = vars.getUserEmail();
haveOAuthToken = vars.getHaveOauthToken();
convObjectIdString =
vars.getConvConnectResponse().getSignedSession().getSession().getObjectId();
convSnapshot = vars.getConvSnapshot();
convConnectResponse = vars.getConvConnectResponse();
if (!vars.hasUdw()) {
useUdw = false;
udwData = null;
} else {
useUdw = true;
udwData = vars.getUdw();
udwObjectId = new SlobId(vars.getUdw().getConnectResponse()
.getSignedSession().getSession().getObjectId());
}
VersionChecker versionChecker = new VersionChecker(rpc, vars.getClientVersion());
// NOTE(danilatos): Use the highest priority timer, since we can't afford to
// let it be starved due to some bug with another non-terminating
// high-priority task. This task runs infrequently and is very minimal so
// the risk of impacting the UI is low.
SchedulerInstance.getHighPriorityTimer().scheduleRepeating(versionChecker,
VERSION_CHECK_INTERVAL_MS, VERSION_CHECK_INTERVAL_MS);
}
final RandomProviderImpl random =
// TODO(ohler): Get a stronger RandomProvider.
RandomProviderImpl.ofSeed(randomSeed);
final RandomBase64Generator random64 = new RandomBase64Generator(new RandomProvider() {
@Override public int nextInt(int upperBound) {
return random.nextInt(upperBound);
}});
final ParticipantId userId;
try {
userId = ParticipantId.of(userIdString);
} catch (InvalidParticipantAddress e1) {
Window.alert("Invalid user id received from server: " + userIdString);
return;
}
convObjectId = new SlobId(convObjectIdString);
idGenerator = new IdHack.MinimalIdGenerator(
IdHack.convWaveletIdFromObjectId(convObjectId),
useUdw ? IdHack.udwWaveletIdFromObjectId(udwObjectId)
// Some code depends on this not to return null, so let's return
// something.
: IdHack.DISABLED_UDW_ID,
random64);
// TODO(ohler): Make the server's response to the contacts RPC indicate
// whether an OAuth token is needed, and enable the button dynamically when
// appropriate, rather than statically.
UIObject.setVisible(Document.get().getElementById("enableAvatarsButton"),
!haveOAuthToken);
@Nullable final LoadWaveService loadWaveService = isLive ? new LoadWaveService(rpc) : null;
@Nullable final ChannelConnectService channelService =
isLive ? new ChannelConnectService(rpc) : null;
new Stages() {
@Override
protected AsyncHolder<StageZero> createStageZeroLoader() {
return new StageZero.DefaultProvider() {
@Override
protected UncaughtExceptionHandler createUncaughtExceptionHandler() {
return WalkaroundUncaughtExceptionHandler.INSTANCE;
}
};
}
@Override
protected AsyncHolder<StageOne> createStageOneLoader(StageZero zero) {
return new StageOne.DefaultProvider(zero) {
protected final ParticipantViewImpl.Helper<ParticipantAvatarDomImpl> participantHelper =
new ParticipantViewImpl.Helper<ParticipantAvatarDomImpl>() {
@Override public void remove(ParticipantAvatarDomImpl impl) {
impl.remove();
}
@Override public ProfilePopupView showParticipation(ParticipantAvatarDomImpl impl) {
return new ProfilePopupWidget(impl.getElement(),
AlignedPopupPositioner.BELOW_RIGHT);
}
};
@Override protected UpgradeableDomAsViewProvider createViewProvider() {
return new FullStructure(createCssProvider()) {
@Override public ParticipantView asParticipant(Element e) {
return e == null ? null : new ParticipantViewImpl<ParticipantAvatarDomImpl>(
participantHelper, ParticipantAvatarDomImpl.of(e));
}
};
}
};
}
@Override
protected AsyncHolder<StageTwo> createStageTwoLoader(final StageOne one) {
return new StageTwo.DefaultProvider(one) {
WaveViewData waveData;
StringMap<DocOp> diffMap = CollectionUtils.createStringMap();
@Override protected DomRenderer createRenderer() {
final BlipQueueRenderer pager = getBlipQueue();
DocRefRenderer docRenderer = new DocRefRenderer() {
@Override
public UiBuilder render(
ConversationBlip blip, IdentityMap<ConversationThread, UiBuilder> replies) {
// Documents are rendered blank, and filled in later when
// they get paged in.
pager.add(blip);
return DocRefRenderer.EMPTY.render(blip, replies);
}
};
RenderingRules<UiBuilder> rules = new MyFullDomRenderer(
getBlipDetailer(), docRenderer, getProfileManager(),
getViewIdMapper(), createViewFactories(), getThreadReadStateMonitor()) {
@Override
public UiBuilder render(Conversation conversation, ParticipantId participant) {
// Same as super class, but using avatars instead of names.
Profile profile = getProfileManager().getProfile(participant);
String id = getViewIdMapper().participantOf(conversation, participant);
ParticipantAvatarViewBuilder participantUi =
ParticipantAvatarViewBuilder.create(id);
participantUi.setAvatar(profile.getImageUrl());
participantUi.setName(profile.getFullName());
return participantUi;
}
};
return new HtmlDomRenderer(ReductionBasedRenderer.of(rules, getConversations()));
}
@Override
protected ProfileManager createProfileManager() {
return ContactsManager.create(rpc);
}
@Override
protected void create(final Accessor<StageTwo> whenReady) {
super.create(whenReady);
}
@Override
protected IdGenerator createIdGenerator() {
return idGenerator;
}
@Override
protected void fetchWave(final Accessor<WaveViewData> whenReady) {
wavelets.updateData(
parseConvWaveletData(
convConnectResponse, convSnapshot,
getDocumentRegistry(), diffMap));
if (useUdw) {
wavelets.updateData(
parseUdwData(
udwData.getConnectResponse(),
udwData.getSnapshot(),
getDocumentRegistry()));
}
Document.get().getElementById(WAVEPANEL_PLACEHOLDER).setInnerText("");
waveData = createWaveViewData();
whenReady.use(waveData);
}
@Override
protected WaveDocuments<LazyContentDocument> createDocumentRegistry() {
IndexedDocumentImpl.performValidation = false;
DocumentFactory<?> dataDocFactory =
ObservablePluggableMutableDocument.createFactory(createSchemas());
DocumentFactory<LazyContentDocument> blipDocFactory =
new DocumentFactory<LazyContentDocument>() {
private final Registries registries = RegistriesHolder.get();
@Override
public LazyContentDocument create(
WaveletId waveletId, String docId, DocInitialization content) {
SimpleDiffDoc diff = SimpleDiffDoc.create(content, diffMap.get(docId));
return LazyContentDocument.create(registries, diff);
}
};
return WaveDocuments.create(blipDocFactory, dataDocFactory);
}
@Override
protected ParticipantId createSignedInUser() {
return userId;
}
@Override
protected String createSessionId() {
// TODO(ohler): Write a note here about what this is and how it
// interacts with walkaround's session management.
return random64.next(6);
}
@Override
protected MuxConnector createConnector() {
return new MuxConnector() {
private void connectWavelet(StaticChannelBinder binder,
ObservableWaveletData wavelet) {
WaveletId waveletId = wavelet.getWaveletId();
SlobId objectId = IdHack.objectIdFromWaveletId(waveletId);
WaveletEntry data = wavelets.get(objectId);
Assert.check(data != null, "Unknown wavelet: %s", waveletId);
if (data.getChannelToken() == null) {
// TODO(danilatos): Handle with a nicer message, and maybe try to
// reconnect later.
Window.alert("Could not open a live connection to this wave. "
+ "It will be read-only, changes will not be saved!");
return;
}
String debugSuffix;
if (objectId.equals(convObjectId)) {
debugSuffix = "-c";
} else if (objectId.equals(udwObjectId)) {
debugSuffix = "-u";
} else {
debugSuffix = "-xxx";
}
ReceiveOpChannel<WaveletOperation> storeChannel =
new GaeReceiveOpChannel<WaveletOperation>(
objectId, data.getSignedSessionString(), data.getChannelToken(),
channelService, Logs.create("gaeroc" + debugSuffix)) {
@Override
protected WaveletOperation parse(ChangeData<JavaScriptObject> message)
throws MessageException {
return serializer.deserializeDelta(
message.getPayload().<DeltaJsoImpl>cast());
}
};
WalkaroundOperationChannel channel = new WalkaroundOperationChannel(
Logs.create("channel" + debugSuffix),
createSubmitService(objectId),
storeChannel, Versions.truncate(wavelet.getVersion()),
data.getSession().getClientId(),
indicator);
String id = ModernIdSerialiser.INSTANCE.serialiseWaveletId(waveletId);
binder.bind(id, channel);
}
@Override
public void connect(Command onOpened) {
if (isLive) {
WaveletOperationalizer operationalizer = getWavelets();
StaticChannelBinder binder = new StaticChannelBinder(
operationalizer, getDocumentRegistry());
for (ObservableWaveletData wavelet : operationalizer.getWavelets()) {
if (useUdw || !IdHack.DISABLED_UDW_ID.equals(wavelet.getWaveletId())) {
connectWavelet(binder, wavelet);
}
}
// HACK(ohler): I haven't tried to understand what the semantics of the callback
// are; perhaps we should invoke it even if the wave is static. (It seems to be
// null though.)
if (onOpened != null) {
onOpened.execute();
}
}
}
@Override
public void close() {
throw new AssertionError("close not implemented");
}
};
}
private SubmitDeltaService createSubmitService(final SlobId objectId) {
return new SubmitDeltaService(rpc, wavelets, objectId) {
@Override
public void requestRevision(final SendOpService.Callback callback) {
loadWaveService.fetchWaveRevision(
wavelets.get(objectId).getSignedSessionString(),
new ConnectCallback() {
@Override public void onData(ConnectResponse data) {
// TODO(danilatos): Update session id etc in the operation channel
// in order for (something equivalent to) this to work.
// But don't have submit delta service keep a reference to this map.
// ALSO TODO: channelToken could be null, if a channel could not be opened.
// In this case the object should be opened as readonly.
//wavelets.updateData(
// new WaveletEntry(id, channelToken, sid, xsrfToken, revision, null));
callback.onSuccess(Versions.truncate(data.getObjectVersion()));
}
@Override public void onConnectionError(Throwable e) {
callback.onConnectionError(e);
}
});
}
};
}
@Override
protected WaveViewService createWaveViewService() {
// unecessary
throw new UnsupportedOperationException();
}
@Override
protected SchemaProvider createSchemas() {
return new ConversationSchemas();
}
@Override
protected Builder installDoodads(Builder doodads) {
doodads = super.installDoodads(doodads);
doodads.use(new ConversationInstaller() {
@Override
public void install(Wavelet w, Conversation c, Registries r) {
WalkaroundAttachmentManager mgr = new WalkaroundAttachmentManager(
new AttachmentInfoService(rpc), logger);
ImageThumbnail.register(r.getElementHandlerRegistry(), mgr,
new DownloadThumbnailAction());
}
});
return doodads;
}
@Override
protected void installFeatures() {
super.installFeatures();
ReadStateSynchronizer.create(FakeReadStateService.create(), getReadMonitor());
}
};
}
@Override
protected AsyncHolder<StageThree> createStageThreeLoader(final StageTwo two) {
return new StageThree.DefaultProvider(two) {
@Override
protected void install() {
// Inhibit if not live; super.install() seems to enable editing in Undercurrent.
// Haven't studied this carefully though.
if (isLive) {
super.install();
}
}
@Override
protected void create(final Accessor<StageThree> whenReady) {
// Prepend an init wave flow onto the stage continuation.
super.create(new Accessor<StageThree>() {
@Override
public void use(StageThree three) {
if (isLive) {
maybeNewWaveSetup(two, three);
UploadToolbarAction.install(three.getEditSession(), three.getEditToolbar());
// HACK(ohler): I haven't tried to understand what the semantics of the callback
// are; perhaps we should invoke it even if the wave is static.
whenReady.use(three);
}
}
});
}
};
}
private void maybeNewWaveSetup(StageTwo two, StageThree three) {
ModelAsViewProvider views = two.getModelAsViewProvider();
Conversation rootConv = two.getConversations().getRoot();
if (looksLikeANewWave(rootConv)) {
BlipView blipUi = views.getBlipView(rootConv.getRootThread().getFirstBlip());
// Needed because startEditing must have an editor already rendered.
two.getBlipQueue().flush();
three.getEditActions().startEditing(blipUi);
}
}
private boolean looksLikeANewWave(Conversation rootConv) {
return Iterables.size(rootConv.getRootThread().getBlips()) == 1
&& rootConv.getRootThread().getFirstBlip().getContent().size() == 4;
}
}.load(null);
}
private WaveViewDataImpl createWaveViewData() {
final WaveViewDataImpl waveData = WaveViewDataImpl.create(
IdHack.waveIdFromConvObjectId(convObjectId));
wavelets.each(new WaveletMap.Proc() {
@Override public void wavelet(WaveletEntry data) {
WaveletDataImpl wavelet = data.getWaveletState();
waveData.addWavelet(wavelet);
}
});
return waveData;
}
private void setupShell() {
DebugMenu menu = new DebugMenu();
boolean shouldShowDebug =
Window.Location.getParameter("debug") != null;
menu.setVisible(shouldShowDebug);
menu.addItem("OOPHM", navigateTaskOophm(Window.Location.getHref(), false));
menu.addItem("Show log", new Task() {
@Override public void execute() {
Walkaround.ensureDomLog();
}
});
menu.addItem("log level 'debug'", navigateTask(
Window.Location.getHref() + "&ll=debug", false));
menu.addItem("Frame: " + Window.Location.getHref(),
navigateTask(Window.Location.getHref(), true));
menu.addItem("Throw Exception", new Task() {
@Override public void execute() {
throw new RuntimeException("TEST EXCEPTION", a());
}
private Exception a() {
return b();
}
private Exception b() {
return new Exception("Nested test exception cause");
}
});
menu.install();
}
private void setupLogging() {
Logs.get().addHandler(new ErrorReportingLogHandler("/gwterr") {
@Override protected void onSevere(String stream) {
alertDomLog(stream);
}
});
}
/**
* If ths DOM log has not been created yet, creates it and draws attention to
* a stream.
*/
private static void alertDomLog(final String attentionStream) {
if (domLogger == null) {
domLogger = LogPanel.createOnStream(Logs.get(), attentionStream);
attachLogPanel();
}
}
/**
* If ths DOM log has not been created yet, creates it.
*/
private static void ensureDomLog() {
if (domLogger == null) {
domLogger = LogPanel.create(Logs.get());
attachLogPanel();
}
}
private static Task navigateTaskOophm(String url, boolean newPage) {
if (!url.endsWith(OOPHM_SUFFIX)) {
url += OOPHM_SUFFIX;
}
return navigateTask(url, newPage);
}
private static Task navigateTask(final String url, final boolean newPage) {
return new Task() {
@Override public void execute() {
if (newPage) {
Window.open(url, "_blank", null);
} else {
Window.Location.assign(url);
}
}
};
}
/** Reveals the log div, and executes a task when done. */
// The async API for this method is intended to support two things: a cool
// spew animation, and also the potential to runAsync the whole LogPanel code.
private static void attachLogPanel() {
Logs.get().addHandler(domLogger);
final Panel logHolder = RootPanel.get("logHolder");
logHolder.setVisible(true);
// Need one layout and paint cycle after revealing it to start animation.
// Use high priority to avoid potential starvation by other tasks if a
// problem is occurring.
SchedulerInstance.getHighPriorityTimer().scheduleDelayed(new Task() {
@Override
public void execute() {
logHolder.add(domLogger);
Style waveStyle = Document.get().getElementById(WAVEPANEL_PLACEHOLDER).getStyle();
Style logStyle = logHolder.getElement().getStyle();
logStyle.setHeight(250, Unit.PX);
waveStyle.setBottom(250, Unit.PX);
}
}, 50);
}
}
| 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.core.client.GWT;
import com.google.gwt.core.client.GWT.UncaughtExceptionHandler;
import com.google.walkaround.util.client.log.Logs.Level;
/**
* Walkaround's uncaught exception handler
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class WalkaroundUncaughtExceptionHandler implements UncaughtExceptionHandler {
public static final WalkaroundUncaughtExceptionHandler INSTANCE =
new WalkaroundUncaughtExceptionHandler();
@Override
public void onUncaughtException(Throwable e) {
e.printStackTrace();
GWT.log(e.getMessage(), e);
Walkaround.logger.log(Level.SEVERE, 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.wave.client.rpc;
import com.google.walkaround.slob.shared.MessageException;
import com.google.walkaround.wave.client.JsUtil;
import com.google.walkaround.wave.shared.SharedConstants;
import org.waveprotocol.wave.client.common.util.JsoView;
/**
* Rpc utilities.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public final class RpcUtil {
private RpcUtil(){}
public static JsoView evalPrefixed(String data) throws MessageException {
if (!data.startsWith(SharedConstants.XSSI_PREFIX)) {
throw new MessageException("Data did not start with XSSI prefix: " + data);
}
return JsUtil.eval(data.substring(SharedConstants.XSSI_PREFIX.length()));
}
}
| 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.rpc;
import com.google.walkaround.slob.client.GenericOperationChannel.SendOpService;
import com.google.walkaround.slob.shared.MessageException;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.wave.client.ClientMessageSerializer;
import com.google.walkaround.wave.shared.SharedConstants.Params;
import com.google.walkaround.wave.shared.SharedConstants.Services;
import com.google.walkaround.wave.shared.WaveSerializer;
import org.waveprotocol.wave.client.common.util.JsoView;
import org.waveprotocol.wave.model.operation.wave.WaveletOperation;
import org.waveprotocol.wave.model.util.CollectionUtils;
import java.util.List;
/**
* Low-level service that submits a delta to a wave. Does not handle being
* called while another delta is still in flight, that is a job for the channel
* layer above.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public abstract class SubmitDeltaService implements SendOpService<WaveletOperation> {
private final Rpc rpc;
private final WaveletMap wavelets;
private final SlobId objectId;
private final WaveSerializer serializer;
public SubmitDeltaService(Rpc rpc, WaveletMap wavelets, SlobId objectId) {
this.rpc = rpc;
this.wavelets = wavelets;
this.objectId = objectId;
this.serializer = new WaveSerializer(new ClientMessageSerializer());
}
@Override
public void submitOperations(int revision, List<WaveletOperation> operations,
final Callback callback) {
rpc.makeRequest(Rpc.Method.POST, Services.SUBMIT_DELTA,
CollectionUtils.newStringMap(
Params.SESSION, wavelets.get(objectId).getSignedSessionString(),
"v", revision + "",
"operations", serializer.serializeOperationBatch(operations)),
new Rpc.RpcCallback() {
@Override
public void onSuccess(String data) throws MessageException {
JsoView json = RpcUtil.evalPrefixed(data);
callback.onSuccess((int) json.getNumber("version"));
}
@Override
public void onConnectionError(Throwable e) {
callback.onConnectionError(e);
}
@Override
public void onFatalError(Throwable e) {
callback.onFatalError(e);
}
});
}
@Override
public void callbackNotNeeded(SendOpService.Callback callback) {
// nothing
}
}
| 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.rpc;
import com.google.gwt.core.client.Duration;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
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.UserAgent;
import org.waveprotocol.wave.model.util.CollectionUtils;
import org.waveprotocol.wave.model.util.IntMap;
import org.waveprotocol.wave.model.util.ReadableStringMap;
import org.waveprotocol.wave.model.util.StringMap;
/**
* Ajax HTTP-Request based implementation of the Rpc interface.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class AjaxRpc implements Rpc {
private enum Result {
OK,
PERMANENT_FAILURE,
RETRYABLE_FAILURE
}
private final class Handle implements RpcHandle {
private final int id;
Handle(int id) {
this.id = id;
}
public int getId() {
return id;
}
@Override public boolean equals(Object other) {
if (other instanceof Handle) {
return id == ((Handle) other).id;
}
return false;
}
@Override public int hashCode() {
return id * 43;
}
@Override
public void drop() {
dropRequest(this);
}
@Override
public boolean isPending() {
return handles.containsKey(id);
}
}
static void dropRequest(Handle handle) {
handles.remove(handle.getId());
}
private static final int MAX_CONSECUTIVE_FAILURES = 20;
/** Root prefix to prepend to service urls */
private final String rpcRoot;
private final ConnectionStateListener listener;
private ConnectionState connectionState = ConnectionState.CONNECTED;
private int consecutiveFailures = 0;
/** Log stream to use */
private static final Log log = Logs.create("rpc");
/** Incrementing id counter */
private static int nextRequestId;
private static IntMap<Handle> handles = CollectionUtils.createIntMap();
/**
* Drops all pending AJAX requests
*/
public static void dropAll() {
handles.clear();
}
/**
* @param rpcRoot root prefix to prepend to service urls
*/
public AjaxRpc(final String rpcRoot, ConnectionStateListener listener) {
this.rpcRoot = rpcRoot;
this.listener = listener;
}
@Override
public RpcHandle makeRequest(Method method, String serviceName, ReadableStringMap<String> params,
final Rpc.RpcCallback rpcCallback) {
final int requestId = nextRequestId;
nextRequestId++;
// See the javadoc for HARD_RELOAD.
if (connectionState == ConnectionState.HARD_RELOAD) {
return new Handle(requestId);
}
final String requestData;
final RequestBuilder.Method httpMethod;
StringBuilder urlBuilder = new StringBuilder(rpcRoot + "/" + serviceName + "?");
// NOTE(danilatos): For some reason, IE6 seems not to perform some requests
// it's already made, resulting in... no data. Inserting some
// unique value into the request seems to fix that.
if (UserAgent.isIE()) {
urlBuilder.append("_no_cache=" + requestId + "" + Duration.currentTimeMillis() + "&");
}
if (method == Method.GET) {
httpMethod = RequestBuilder.GET;
addParams(urlBuilder, params);
requestData = "";
} else {
httpMethod = RequestBuilder.POST;
requestData = addParams(new StringBuilder(), params).toString();
}
final String url = urlBuilder.toString();
RequestBuilder r = new RequestBuilder(httpMethod, url);
if (method == Method.POST) {
r.setHeader("Content-Type", "application/x-www-form-urlencoded");
r.setHeader("X-Same-Domain", "true");
}
log.log(Level.INFO, "RPC Request, id=", requestId, " method=", httpMethod,
" urlSize=", url.length(), " bodySize=", requestData.length());
class RpcRequestCallback implements RequestCallback {
@Override public void onResponseReceived(Request request, Response response) {
RpcHandle handle = handles.get(requestId);
if (handle == null) {
// It's been dropped
log.log(Level.INFO, "RPC SuccessDrop, id=", requestId);
return;
}
// Clear it now, before callbacks
removeHandle();
int statusCode = response.getStatusCode();
String data = response.getText();
Result result;
if (statusCode < 100) {
result = Result.RETRYABLE_FAILURE;
maybeSetConnectionState(ConnectionState.OFFLINE);
} else if (statusCode == 200) {
result = Result.OK;
maybeSetConnectionState(ConnectionState.CONNECTED);
consecutiveFailures = 0;
} else if (statusCode >= 500) {
result = Result.RETRYABLE_FAILURE;
consecutiveFailures++;
if (consecutiveFailures > MAX_CONSECUTIVE_FAILURES) {
maybeSetConnectionState(ConnectionState.OFFLINE);
} else {
maybeSetConnectionState(ConnectionState.CONNECTED);
}
} else {
result = Result.PERMANENT_FAILURE;
maybeSetConnectionState(ConnectionState.SOFT_RELOAD);
}
switch (result) {
case OK:
log.log(Level.INFO, "RPC Success, id=", requestId);
try {
rpcCallback.onSuccess(data);
} catch (MessageException e) {
// Semi-HACK(danilatos): Treat parse errors as login problems
// due to loading a login or authorization page. (It's unlikely
// we'd otherwise get a parse error from a 200 OK result).
// The simpler solution of detecting redirects is not possible
// with XmlHttpRequest, the web is unfortunately broken.
// TODO(danilatos) Possible alternatives:
// either change our server side to not require
// login through web.xml but to check if UserService says currentUser==null (or
// whatever it does if not logged in) and return a well-defined "not logged in"
// response instead, or to prefix all responses from the server with a fixed string
// (like we do with "OK" elsewhere) and assume not logged in if that prefix is
// missing. We could strip off that prefix here and make it transparent to the
// callbacks.
maybeSetConnectionState(ConnectionState.LOGGED_OUT);
error(new Exception("RPC failed due to message exception, treating as auth failure"
+ ", status code: " + statusCode + ", data: " + data));
}
break;
case RETRYABLE_FAILURE:
error(new Exception("RPC failed, status code: " + statusCode + ", data: " + data));
break;
case PERMANENT_FAILURE:
fatal(new Exception("RPC bad request, status code: " + statusCode + ", data: " + data));
break;
default:
throw new AssertionError("Unknown result " + result);
}
}
@Override public void onError(Request request, Throwable exception) {
if (!handles.containsKey(requestId)) {
log.log(Level.INFO, "RPC FailureDrop, id=", requestId, exception.getMessage());
return;
}
removeHandle();
error(exception);
}
private void fatal(Throwable e) {
log.log(Level.WARNING, "RPC Bad Request, id=", requestId, e.getMessage(),
"Request url:" + url, e);
rpcCallback.onFatalError(e);
}
private void error(Throwable e) {
log.log(Level.WARNING, "RPC Failure, id=", requestId, e.getMessage(),
"Request url:" + url, e);
rpcCallback.onConnectionError(e);
}
private void removeHandle() {
handles.remove(requestId);
}
}
RpcRequestCallback innerCallback = new RpcRequestCallback();
try {
Request gwtReq = r.sendRequest(requestData, innerCallback);
Handle handle = new Handle(requestId);
handles.put(handle.getId(), handle);
return handle;
} catch (RequestException e) {
// TODO(danilatos) Decide if this should be a badRequest.
innerCallback.error(e);
return null;
}
}
/**
* {@inheritDoc}
*
* If a change occurs, notifies the listener.
*/
@Override
public void maybeSetConnectionState(ConnectionState newState) {
if (newState != connectionState && connectionState.canTransitionTo(newState)) {
connectionState = newState;
listener.connectionStateChanged(connectionState);
}
}
private StringBuilder addParams(final StringBuilder b, ReadableStringMap<String> params) {
params.each(new StringMap.ProcV<String>() {
@Override public void apply(String key, String value) {
if (value != null) {
b.append(
URL.encodeQueryString(key) + "=" +
URL.encodeQueryString(value) + "&");
}
}
});
return 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.wave.client.rpc;
import com.google.common.base.Preconditions;
import com.google.walkaround.slob.shared.MessageException;
import org.waveprotocol.wave.model.util.ReadableStringMap;
/**
* Interface for an RPC mechanism.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public interface Rpc {
public enum ConnectionState {
/** Normal. */
CONNECTED,
/** Cannot connect to server, or too many "retryable" failures. */
OFFLINE,
/** Authentication problem - user needs to log back in. */
LOGGED_OUT,
/** A refresh is required, at the user's discretion. */
SOFT_RELOAD,
/**
* A refresh is required, and no further rpcs should be sent. The server
* could send a signal to the client to put it into this state, e.g. if we
* are fixing a critical DOS bug or if we are making an incompatible change
* to the client-server protocol.
*/
HARD_RELOAD;
/**
* Returns if the state transition is permitted.
*
* States can only monotonically increase after reaching SOFT_RELOAD.
*
* E.g. once we're broken in some way that is not likely to be recoverable,
* and we must reload, we shouldn't leave that state due to some unrelated
* RPC happening to succeed.
*
*/
public boolean canTransitionTo(ConnectionState newState) {
Preconditions.checkNotNull(newState, "Null newState");
boolean onlyMonotonic = this.ordinal() >= ConnectionState.SOFT_RELOAD.ordinal();
return !onlyMonotonic || newState.ordinal() > this.ordinal();
}
}
public interface ConnectionStateListener {
void connectionStateChanged(ConnectionState newConnectionState);
}
enum Method {
GET,
POST;
}
public interface RpcHandle {
/**
* Drops the rpc request this is a handle for. Neither its success or
* failure methods will be called after this. It is always valid to call
* this method.
*/
void drop();
/**
* @return true if the request is still pending. false if either the success
* or failure methods have been called (or are being called), or if
* the request was dropped (by calling {@link #drop()}).
*/
boolean isPending();
}
public interface RpcCallback {
/**
* Called on success with respect to the RPC layer.
*
* The implementor may throw {@link MessageException} if the data is in fact
* invalid with respect to the application logic. This will then be treated
* as a fatal error.
*/
void onSuccess(String data) throws MessageException;
/**
* Called when some problem occurred in the RPC layer, and the request may
* be retryable.
*
* Examples include server 500 errors, and connection time outs.
*/
void onConnectionError(Throwable e);
/**
* Called for fatal errors where the request would not be retryable.
*
* Examples include 40x status codes and garbled response data.
*/
void onFatalError(Throwable e);
}
/**
* Make a request to the backend.
*
* @param serviceName RPC service name (e.g. "fetch")
* @param params parameter key value pairs. For convenience, null values are
* accepted, and that parameter is just ignored.
* @param rpcCallback called back on success or failure.
* @return a handle to the request, or null if sending failed
*/
RpcHandle makeRequest(Method method,
String serviceName, ReadableStringMap<String> params, final Rpc.RpcCallback rpcCallback);
/**
* Modifies the state if the transition is permitted.
*/
void maybeSetConnectionState(ConnectionState 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.wave.client.rpc;
import com.google.walkaround.slob.shared.MessageException;
import org.waveprotocol.wave.client.common.util.JsoView;
import org.waveprotocol.wave.model.util.CollectionUtils;
import java.util.List;
/**
* Fetches attachment information.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class AttachmentInfoService {
public interface Callback {
void onSuccess(JsoView data);
void onConnectionError(Throwable e);
void onFatalError(Throwable e);
}
private final Rpc rpc;
private final String serviceName = "attachmentinfo";
public AttachmentInfoService(Rpc rpc) {
this.rpc = rpc;
}
public void fetchInfo(List<String> attachmentIds, final Callback callback) {
StringBuilder b = new StringBuilder();
for (String id : attachmentIds) {
if (b.length() > 0) {
b.append(',');
}
if (id.contains(",")) {
throw new IllegalArgumentException("Attachment id '" + id + "' contains a comma");
}
b.append(id);
}
rpc.makeRequest(Rpc.Method.POST, serviceName, CollectionUtils.newStringMap(
"ids", b.toString()),
new Rpc.RpcCallback() {
@Override
public void onSuccess(String data) throws MessageException {
JsoView json = RpcUtil.evalPrefixed(data);
callback.onSuccess(json);
}
@Override
public void onConnectionError(Throwable e) {
callback.onConnectionError(e);
}
@Override
public void onFatalError(Throwable e) {
callback.onFatalError(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.wave.client.rpc;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.walkaround.slob.client.ChangeDataParser;
import com.google.walkaround.slob.shared.ChangeData;
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.shared.SharedConstants.Params;
import com.google.walkaround.wave.shared.SharedConstants.Services;
import org.waveprotocol.wave.client.common.util.JsoView;
import org.waveprotocol.wave.model.util.CollectionUtils;
/**
* Handles getting a channel token for connecting a browser channel, and
* fetching missing messages.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class ChannelConnectService {
public interface Callback {
void onConnect(String channelToken);
void onKnownHeadRevision(int headRevision);
void onHistoryItem(int resultingRevision, ChangeData<JavaScriptObject> message);
void onConnectionError(Throwable e);
void onFatalError(Throwable e);
}
private final Log log = Logs.create("channel-connect");
private final Rpc rpc;
public ChannelConnectService(Rpc rpc) {
this.rpc = rpc;
}
public void connect(String signedSessionString,
final int revision, final Callback callback) {
rpc.makeRequest(Rpc.Method.POST, Services.CHANNEL,
CollectionUtils.newStringMap(
Params.SESSION, signedSessionString,
Params.REVISION, revision + ""),
new Rpc.RpcCallback() {
@Override
public void onSuccess(String data) throws MessageException {
JsoView json = RpcUtil.evalPrefixed(data);
if (json.containsKey("error")) {
onConnectionError(new Exception(json.getString("error")));
} else {
callback.onConnect(json.getString("token"));
JsoView history = json.getJsoView("history");
if (history.getNumber("length") > 0) {
sendHistoryItems(history, callback, revision);
}
// The head revision might be greater than expected if some
// history items were missed, so let's give the listener
// as much information as possible.
callback.onKnownHeadRevision((int) json.getNumber("head"));
}
}
@Override
public void onConnectionError(Throwable e) {
callback.onConnectionError(e);
}
@Override
public void onFatalError(Throwable e) {
callback.onFatalError(e);
}
});
}
/**
* This has the same method signature as {@link #connect}, but does not try to
* reconnect. Because of implementation details, the server side
* implementation of connect is more expensive than just a history fetch (as
* it consumes a session id, which is a finite resource), so we're keeping
* them separate for now. But they could potentially be merged.
*
* TODO(ohler): We no longer consume a session id, update the above comment.
*/
public void fetchHistory(final String signedSessionString,
final int startRevision, final Callback callback) {
rpc.makeRequest(Rpc.Method.POST, Services.HISTORY,
CollectionUtils.newStringMap(
Params.SESSION, signedSessionString,
Params.START_REVISION, startRevision + ""),
new Rpc.RpcCallback() {
@Override
public void onSuccess(String data) throws MessageException {
JsoView json = RpcUtil.evalPrefixed(data).getJsoView("history");
int len = sendHistoryItems(json, callback, startRevision);
boolean hasMore = json.getBoolean("more");
// In case the result is batched, we'll keep fetching.
if (hasMore) {
// TODO(danilatos): Move this logic into GaeReceiveOpChannel,
// keep this class dumb.
log.log(Level.INFO,
"fetch history returned incomplete result, retrying for the rest");
fetchHistory(signedSessionString, startRevision + len, callback);
}
}
@Override
public void onConnectionError(Throwable e) {
callback.onConnectionError(e);
}
@Override
public void onFatalError(Throwable e) {
callback.onFatalError(e);
}
});
}
private static int sendHistoryItems(JsoView json, Callback callback, int startRevision) {
int len = (int) json.getNumber("length");
if (len == 0) {
callback.onFatalError(new Exception("history fetch returned empty results"));
return 0;
}
for (int i = 0; i < len; i++) {
JsoView item = json.getJsoView(i);
callback.onHistoryItem(startRevision + i + 1, // + 1 for resulting revision
ChangeDataParser.fromJson(item));
}
return len;
}
}
| 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.rpc;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.walkaround.proto.ObjectSessionProto;
import com.google.walkaround.slob.shared.SlobId;
import org.waveprotocol.wave.model.util.CollectionUtils;
import org.waveprotocol.wave.model.util.StringMap;
import org.waveprotocol.wave.model.wave.data.impl.WaveletDataImpl;
import javax.annotation.Nullable;
/**
* Registry of wavelet data for current wave.
*
* @author danilatos@google.com (Daniel Danilatos)
* @author ohler@google.com (Christian Ohler)
*/
public class WaveletMap {
public static class WaveletEntry {
private final SlobId objectId;
// This is the serialized JSON form of the SignedObjectSession protobuf. We
// store it in serialized form to avoid the cost of re-serializing it for
// every request that we send.
@Nullable private final String signedSessionString;
@Nullable private final ObjectSessionProto session;
// Null means we can't get a live stream of updates for this object.
@Nullable private final String channelToken;
private final WaveletDataImpl waveletState;
public WaveletEntry(SlobId objectId,
@Nullable String signedSessionString,
@Nullable ObjectSessionProto session,
@Nullable String channelToken,
WaveletDataImpl waveletState) {
this.objectId = checkNotNull(objectId, "Null objectId");
this.signedSessionString = signedSessionString;
this.session = session;
this.channelToken = channelToken;
this.waveletState = checkNotNull(waveletState, "Null waveletState");
}
public SlobId getObjectId() {
return objectId;
}
@Nullable public String getSignedSessionString() {
return signedSessionString;
}
@Nullable public ObjectSessionProto getSession() {
return session;
}
@Nullable public String getChannelToken() {
return channelToken;
}
public WaveletDataImpl getWaveletState() {
return waveletState;
}
@Override public String toString() {
return "WaveletEntry(" + objectId + ", " + signedSessionString + ", " + session + ", "
+ channelToken + ", " + waveletState + ")";
}
}
public interface Proc {
void wavelet(WaveletEntry data);
}
private final StringMap<WaveletEntry> wavelets = CollectionUtils.createStringMap();
/**
* Updates the data for the given wavelet (the id is part of the data)
*/
public void updateData(WaveletEntry newEntry) {
wavelets.put(newEntry.getObjectId().getId(), newEntry);
}
public WaveletEntry get(SlobId id) {
return wavelets.get(id.getId());
}
public boolean contains(SlobId id) {
return wavelets.containsKey(id.getId());
}
public void each(final Proc proc) {
wavelets.each(new StringMap.ProcV<WaveletEntry>() {
@Override public void apply(String key, WaveletEntry data) {
proc.wavelet(data);
}
});
}
public int countEntries() {
return wavelets.countEntries();
}
}
| 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.rpc;
import com.google.common.base.Preconditions;
import com.google.walkaround.proto.ConnectResponse;
import com.google.walkaround.proto.WalkaroundWaveletSnapshot;
import com.google.walkaround.proto.WaveletDiffSnapshot;
import com.google.walkaround.proto.jso.ConnectResponseJsoImpl;
import com.google.walkaround.slob.shared.MessageException;
import com.google.walkaround.slob.shared.SlobId;
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.ClientMessageSerializer;
import com.google.walkaround.wave.client.rpc.WaveletMap.WaveletEntry;
import com.google.walkaround.wave.shared.IdHack;
import com.google.walkaround.wave.shared.SharedConstants.Params;
import com.google.walkaround.wave.shared.SharedConstants.Services;
import com.google.walkaround.wave.shared.WaveSerializer;
import org.waveprotocol.wave.model.document.operation.DocOp;
import org.waveprotocol.wave.model.util.CollectionUtils;
import org.waveprotocol.wave.model.util.StringMap;
import org.waveprotocol.wave.model.wave.data.DocumentFactory;
import org.waveprotocol.wave.model.wave.data.impl.WaveletDataImpl;
/**
* Service that checks current version of wave.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
// TODO(ohler): rename to something like WaveletConnectService
public class LoadWaveService {
private static final Log log = Logs.create("loadwave");
public interface LoadWaveCallback {
void onData(WaveletEntry data);
void onConnectionError(Throwable e);
}
public interface ConnectCallback {
void onData(ConnectResponse data);
void onConnectionError(Throwable e);
}
private final Rpc rpc;
public LoadWaveService(Rpc rpc) {
this.rpc = rpc;
}
// TODO(ohler): rename to connect?
public void fetchWaveRevision(String signedSessionString,
final ConnectCallback callback) {
rpc.makeRequest(Rpc.Method.GET, Services.CONNECT,
CollectionUtils.newStringMap(Params.SESSION, signedSessionString),
new Rpc.RpcCallback() {
@Override
public void onSuccess(String data) throws MessageException {
log.log(Level.DEBUG, data);
ConnectResponseJsoImpl connectResponse = RpcUtil.evalPrefixed(data).cast();
callback.onData(connectResponse);
}
@Override
public void onFatalError(Throwable e) {
throw new RuntimeException(e);
}
@Override
public void onConnectionError(Throwable e) {
callback.onConnectionError(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.wave.shared;
import com.google.walkaround.proto.Delta;
import com.google.walkaround.proto.OperationBatch;
import com.google.walkaround.proto.ProtocolWaveletOperation;
import com.google.walkaround.proto.WalkaroundWaveletSnapshot;
import com.google.walkaround.proto.WaveletDiffSnapshot;
import com.google.walkaround.slob.shared.MessageException;
/**
* Interface for both server and client side serializer implementations. This
* basic functionality implemented by ClientWaveSerializer and
* ServerWaveSerializer allows to turn Wavelets and Deltas to and from JSON in
* those two environments.
*
* @author piotrkaleta@google.com (Piotr Kaleta)
*/
public interface MessageSerializer {
String serializeWavelet(WalkaroundWaveletSnapshot in);
WalkaroundWaveletSnapshot deserializeWavelet(String in) throws MessageException;
String serializeOp(ProtocolWaveletOperation in);
ProtocolWaveletOperation deserializeOp(String in) throws MessageException;
String serializeDiff(WaveletDiffSnapshot in);
WaveletDiffSnapshot deserializeDiff(String in) throws MessageException;
String serializeOperationBatch(OperationBatch in);
OperationBatch deserializeOperationBatch(String in) throws MessageException;
String serializeDelta(Delta in);
Delta deserializeDelta(String in) 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.shared;
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;
/**
* A factory for creating message objects.
*
* @author zdwang@google.com (David Wang)
*/
public interface MessageFactory {
OperationBatch createOperationBatch();
ProtocolWaveletOperation createWaveOp();
KeyValuePair createDocumentKeyValuePair();
KeyValueUpdate createDocumentKeyValueUpdate();
ElementStart createDocumentElementStart();
ReplaceAttributes createDocumentReplaceAttributes();
UpdateAttributes createDocumentUpdateAttributes();
AnnotationBoundary createDocumentAnnotationBoundary();
Component createDocumentOperationComponent();
ProtocolDocumentOperation createDocumentOperation();
MutateDocument createMutateDocument();
WalkaroundDocumentSnapshot createDocumentSnapshot();
WalkaroundWaveletSnapshot createWaveletSnapshot();
WaveletDiffSnapshot createWaveletDiffSnapshot();
DocumentDiffSnapshot createDocumentDiffSnapshot();
Delta createDelta();
}
| 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.shared;
import com.google.walkaround.proto.ProtocolDocumentOperation;
import com.google.walkaround.proto.ProtocolWaveletOperation;
import com.google.walkaround.proto.ProtocolWaveletOperation.MutateDocument;
import com.google.walkaround.wave.shared.MessageWrapperDocOp.DocOpMessageProvider;
import org.waveprotocol.wave.model.document.operation.DocInitialization;
import org.waveprotocol.wave.model.document.operation.DocOp;
import org.waveprotocol.wave.model.document.operation.automaton.DocOpAutomaton.ViolationCollector;
import org.waveprotocol.wave.model.document.operation.impl.DocOpUtil;
import org.waveprotocol.wave.model.document.operation.impl.DocOpValidator;
import org.waveprotocol.wave.model.operation.wave.AddParticipant;
import org.waveprotocol.wave.model.operation.wave.BlipContentOperation;
import org.waveprotocol.wave.model.operation.wave.NoOp;
import org.waveprotocol.wave.model.operation.wave.RemoveParticipant;
import org.waveprotocol.wave.model.operation.wave.WaveletBlipOperation;
import org.waveprotocol.wave.model.operation.wave.WaveletOperation;
import org.waveprotocol.wave.model.operation.wave.WaveletOperationContext;
import org.waveprotocol.wave.model.wave.InvalidParticipantAddress;
import org.waveprotocol.wave.model.wave.ParticipantId;
/**
* A factory for creating operations from messages.
*
* @author Alexandre Mah
*/
public final class OperationFactory {
/** Private default constructor to enforce noninstantiability. */
private OperationFactory() {}
private static final WaveletOperationContext DUMMY_CONTEXT = new WaveletOperationContext(
null, 0L, 0L);
public static class InvalidInputException extends Exception {
private static final long serialVersionUID = 626293536856959309L;
public InvalidInputException(String message) {
super(message);
}
public InvalidInputException(Throwable cause) {
super(cause);
}
public InvalidInputException(String message, Throwable cause) {
super(message, cause);
}
}
/**
* Creates a WaveletOperation with a dummy context.
*
* @param message The message that should be contained within the
* WaveletOperation.
* @return The newly-created WaveletOperation.
*/
public static WaveletOperation createContextFreeWaveletOperation(
ProtocolWaveletOperation message) throws InvalidInputException {
return createWaveletOperation(DUMMY_CONTEXT, message);
}
/**
* Deserializes a wavelet-operation message.
*
* @param context operation context for the operation
* @param message operation message
* @param checkWellFormed If we should check for wellformness of deserialised DocOp
* @return an operation described by {@code message}
*/
public static WaveletOperation createWaveletOperation(WaveletOperationContext context,
ProtocolWaveletOperation message, boolean checkWellFormed)
throws InvalidInputException {
try {
if (message.hasNoOp() && message.getNoOp()) {
return new NoOp(context);
} else if (message.getAddParticipant() != null && !message.getAddParticipant().isEmpty()) {
return new AddParticipant(context, ParticipantId.of(message.getAddParticipant()));
} else if (message.getRemoveParticipant() != null
&& !message.getRemoveParticipant().isEmpty()) {
return new RemoveParticipant(context, ParticipantId.of(message.getRemoveParticipant()));
} else if (message.getMutateDocument() != null) {
return createBlipOperation(context, message, checkWellFormed);
}
throw new IllegalArgumentException("Unsupported operation: " + message);
} catch (InvalidParticipantAddress e) {
throw new RuntimeException(e);
}
}
/**
* Deserializes a wavelet-operation message. Checsk for wellformness of deserialised DocOp
*
* @param context operation context for the operation
* @param message operation message
* @return an operation described by {@code message}
*/
public static WaveletOperation createWaveletOperation(
WaveletOperationContext context, ProtocolWaveletOperation message)
throws InvalidInputException {
return createWaveletOperation(context, message, true);
}
/**
* Creates a wavelet-blip operation from a message.
*
* @param context
* @param message
* @param checkWellFormed If we should check for wellformness of deserialised DocOp
* @return a wavelet-blip operation described by {@code message}, or {@code null} if
* {@code message} does not describe a blip operation.
*/
private static WaveletBlipOperation createBlipOperation(WaveletOperationContext context,
ProtocolWaveletOperation message, boolean checkWellFormed)
throws InvalidInputException {
if (message.getMutateDocument() != null) {
MutateDocument opMessage = message.getMutateDocument();
return new WaveletBlipOperation(opMessage.getDocumentId(), new BlipContentOperation(
context, createDocumentOperation(opMessage.getDocumentOperation(), checkWellFormed)));
}
throw new InvalidInputException("Failed to create blip operation for message " + message);
}
/**
* Create an implementation of DocumentOperation.
*
* @param message The message representing the document operation.
* @param checkWellFormed If we should check for wellformness of deserialised DocOp
* @return The created operation.
*/
public static DocOp createDocumentOperation(
final ProtocolDocumentOperation message, boolean checkWellFormed)
throws InvalidInputException {
return createDocumentOperation(new DocOpMessageProvider() {
@Override
public ProtocolDocumentOperation getContent() {
return message;
}
}, checkWellFormed);
}
/**
* Create an implementation of DocumentOperation.
*
* @param input The provider of the message to wrap.
* @param checkWellFormed If we should check for wellformness of deserialised DocOp
* @return The created operation.
*/
private static DocOp createDocumentOperation(
final DocOpMessageProvider input, boolean checkWellFormed) throws InvalidInputException {
DocOp value = new MessageWrapperDocOp(input, checkWellFormed);
if (checkWellFormed) {
try {
if (!DocOpValidator.isWellFormed(null, value)) {
// Check again, collecting violations this time.
ViolationCollector v = new ViolationCollector();
DocOpValidator.isWellFormed(v, value);
throw new InvalidInputException("Attempt to build ill-formed operation ("
+ v + "): " + value);
}
} catch (MessageWrapperDocOp.DelayedInvalidInputException e) {
throw new InvalidInputException("Caught DelayedInvalidInputException while validating: "
// Append e's message to our own message here. It's not
// enough to have e's message somewhere in the cause chain
// because some places only log the getMessage() of our
// exception.
+ e + ", " + input, e);
}
}
return value;
}
/**
* Create an implementation of DocumentOperation.
* Checks for wellformness of deserialised DocOp.
*
* @param message The message representing the document operation.
* @return The created operation.
*/
public static DocOp createDocumentOperation(final ProtocolDocumentOperation message)
throws InvalidInputException {
return createDocumentOperation(message, true);
}
/**
* Creates a document initialization from an operation message.
*
* @param message The message representing the document operation.
* @param checkWellFormed If we should check for well-formedness of deserialised DocOp
* @return The created operation.
*/
public static DocInitialization createDocumentInitialization(
ProtocolDocumentOperation message, boolean checkWellFormed) throws InvalidInputException {
return DocOpUtil.asInitialization(createDocumentOperation(message, checkWellFormed));
}
/**
* Creates a document initialization from an operation message.
* Checks for wellformness of deserialised DocOp.
*
* @param message The message representing the document operation.
* @return The created operation.
*/
public static DocInitialization createDocumentInitialization(ProtocolDocumentOperation message)
throws InvalidInputException {
return createDocumentInitialization(message, 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.shared;
/**
* Fetches a segment of contacts from a user's contacts list.
*
* @author hearnden@google.com (David Hearnden)
*/
public interface ContactsService {
/** Maximum number of contacts that can be fetched with a single call. */
int MAX_SIZE = 100;
/**
* A contact.
*/
public interface Contact {
/** Returns the email address; never null. */
String getAddress();
/** Returns the full name of this contact; may be null. */
String getName();
/** Returns the id of the photo for this contact; may be null. */
String getPhotoId();
}
/**
* A list of contacts.
*/
public interface ContactList {
/** @return number of contacts in this list. */
int size();
/** @return contact at {@code i}. */
Contact get(int i);
}
/** Callback for results. */
interface Callback {
void onSuccess(ContactList result);
void onFailure();
}
/**
* Fetches a segment of a user's contacts list.
*
* @param from first index to retrieve, inclusive
* @param to last index to retrieve, exclusive
* @param callback callback to notify with results
* @throws IllegalArgumentException if the range is invalid.
*/
void fetch(int from, int to, Callback callback);
}
| 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.shared;
import com.google.common.base.Preconditions;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.util.shared.RandomBase64Generator;
import org.waveprotocol.wave.model.id.IdConstants;
import org.waveprotocol.wave.model.id.IdGenerator;
import org.waveprotocol.wave.model.id.SimplePrefixEscaper;
import org.waveprotocol.wave.model.id.WaveId;
import org.waveprotocol.wave.model.id.WaveletId;
import org.waveprotocol.wave.model.id.WaveletName;
/**
* Hacks pertaining to wave/wavelet ids.
*
* On the client, wave IDs are derived from a fixed domain and the object id of
* the conversational wavelet. Wavelet IDs are derived from the same fixed
* domain and the object id of the wavelet (conversational or udw).
*
* On the server, we use FAKE_WAVELET_NAME.
*
* @author ohler@google.com (Christian Ohler)
*/
public class IdHack {
public static class StubIdGenerator implements IdGenerator {
@Override public WaveId newWaveId() {
throw new AssertionError("Not implemented");
}
@Override public WaveletId newConversationWaveletId() {
throw new AssertionError("Not implemented");
}
@Override public WaveletId newConversationRootWaveletId() {
throw new AssertionError("Not implemented");
}
@Override public WaveletId newUserDataWaveletId(String address) {
throw new AssertionError("Not implemented");
}
@Override public String newBlipId() {
throw new AssertionError("Not implemented");
}
@Deprecated @Override public String peekBlipId() {
throw new AssertionError("Not implemented");
}
@Override public String newDataDocumentId() {
throw new AssertionError("Not implemented");
}
@Override public String newUniqueToken() {
throw new AssertionError("Not implemented");
}
@Override public String newId(String namespace) {
throw new AssertionError("Not implemented");
}
@Override public String getDefaultDomain() {
throw new AssertionError("Not implemented");
}
}
public static final int BLIP_ID_LENGTH_CHARS = 8;
public static class MinimalIdGenerator extends StubIdGenerator {
private final WaveletId convRootId;
private final WaveletId udwId;
private final RandomBase64Generator random64;
private String nextBlipId = null;
public MinimalIdGenerator(WaveletId convRootId, WaveletId udwId,
RandomBase64Generator random64) {
Preconditions.checkNotNull(convRootId, "Null convRootId");
Preconditions.checkNotNull(udwId, "Null udwId");
Preconditions.checkNotNull(random64, "Null random64");
this.convRootId = convRootId;
this.udwId = udwId;
this.random64 = random64;
}
@Override public String toString() {
return "MinimalIdGenerator(" + convRootId + ", " + udwId + ")";
}
@Override public String newBlipId() {
String ret = peekBlipId();
nextBlipId = null;
return ret;
}
@Deprecated // TODO(danilatos): Check to see if we can fix the code that calls this.
@Override
public String peekBlipId() {
if (nextBlipId == null) {
nextBlipId = createBlipId();
}
return nextBlipId;
}
private String createBlipId() {
return joinTokens(IdConstants.BLIP_PREFIX, random64.next(BLIP_ID_LENGTH_CHARS));
}
// TODO(ohler): Rename this method to getConversationRootWaveletId().
@Override public WaveletId newConversationRootWaveletId() {
return convRootId;
}
// TODO(ohler): Rename this method to getUserDataWaveletId().
@Override public WaveletId newUserDataWaveletId(String address) {
return udwId;
}
}
// TODO(ohler): inject
private static final String DOMAIN = "walkaround";
private static String joinTokens(String... tokens) {
return SimplePrefixEscaper.DEFAULT_ESCAPER.join(IdConstants.TOKEN_SEPARATOR, tokens);
}
private static String[] splitTokens(String s) {
return SimplePrefixEscaper.DEFAULT_ESCAPER.split(IdConstants.TOKEN_SEPARATOR, s);
}
/**
* This is the UDW id that the client uses internally if UDWs are disabled.
*/
public static final WaveletId DISABLED_UDW_ID =
WaveletId.of("disabledudwdomain.invalid", "disabledudwid");
/**
* The wavelet name that the object store model uses.
*/
public static final WaveletName FAKE_WAVELET_NAME =
WaveletName.of(
WaveId.of("fakewavedomain.invalid", "fakewaveid"),
WaveletId.of("fakewaveletdomain.invalid", "fakewaveletid"));
public static WaveId waveIdFromConvObjectId(SlobId convObjectId) {
return WaveId.of(DOMAIN,
joinTokens(IdConstants.WAVE_PREFIX, convObjectId.getId()));
}
public static WaveletId convWaveletIdFromObjectId(SlobId objectId) {
return WaveletId.of(DOMAIN,
joinTokens(IdConstants.CONVERSATION_WAVELET_PREFIX, objectId.getId()));
}
public static WaveletId udwWaveletIdFromObjectId(SlobId objectId) {
return WaveletId.of(DOMAIN,
joinTokens(IdConstants.USER_DATA_WAVELET_PREFIX, objectId.getId()));
}
public static WaveletName convWaveletNameFromConvObjectId(SlobId convObjectId) {
return WaveletName.of(
waveIdFromConvObjectId(convObjectId),
convWaveletIdFromObjectId(convObjectId));
}
public static WaveletName udwWaveletNameFromConvObjectIdAndUdwObjectId(
SlobId convObjectId, SlobId udwObjectId) {
return WaveletName.of(
waveIdFromConvObjectId(convObjectId), udwWaveletIdFromObjectId(udwObjectId));
}
public static SlobId objectIdFromWaveletId(WaveletId waveletId) {
String[] tokens = splitTokens(waveletId.getId());
Preconditions.checkArgument(tokens.length == 2,
"Wavelet id does not consist of two tokens: %s", waveletId);
if (IdConstants.CONVERSATION_WAVELET_PREFIX.equals(tokens[0])
|| IdConstants.USER_DATA_WAVELET_PREFIX.equals(tokens[0])) {
return new SlobId(tokens[1]);
} else {
throw new RuntimeException("Unknown prefix in wavelet id: " + waveletId);
}
}
}
| 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.shared;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
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.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.slob.shared.MessageException;
import com.google.walkaround.wave.shared.OperationFactory.InvalidInputException;
import org.waveprotocol.wave.model.document.operation.DocInitialization;
import org.waveprotocol.wave.model.document.operation.DocOp;
import org.waveprotocol.wave.model.document.operation.algorithm.DocOpCollector;
import org.waveprotocol.wave.model.document.operation.impl.DocOpBuilder;
import org.waveprotocol.wave.model.id.IdUtil;
import org.waveprotocol.wave.model.id.ModernIdSerialiser;
import org.waveprotocol.wave.model.id.WaveletId;
import org.waveprotocol.wave.model.id.WaveletName;
import org.waveprotocol.wave.model.operation.wave.WaveletOperation;
import org.waveprotocol.wave.model.operation.wave.WaveletOperationContext;
import org.waveprotocol.wave.model.util.CollectionUtils;
import org.waveprotocol.wave.model.util.ReadableStringMap.ProcV;
import org.waveprotocol.wave.model.util.StringMap;
import org.waveprotocol.wave.model.version.HashedVersion;
import org.waveprotocol.wave.model.wave.InvalidParticipantAddress;
import org.waveprotocol.wave.model.wave.ParticipantId;
import org.waveprotocol.wave.model.wave.data.DocumentFactory;
import org.waveprotocol.wave.model.wave.data.impl.BlipDataImpl;
import org.waveprotocol.wave.model.wave.data.impl.WaveletDataImpl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Class for serializing and deserializing wavelets and deltas to and from JSON.
* It is meant to be used both by client as well as server.
*
* It works in two stages. First it serializes either wavelet or delta into an
* instance of one of protobuf-generated classes. Then it uses specific
* server or client version of serializer to turn Message into JSON
* representation as String. Concrete serializers (ServerWaveSerializer and
* ClientWaveSerializer) use classes generated by PST translator in order to
* create JSON representations. The reverse process takes place when
* deserializing back to Wavelet or Delta object
*
* @author piotrkaleta@google.com (Piotr Kaleta)
*/
public class WaveSerializer {
private static class DocDiff {
private static final DocOp EMPTY_OP = new DocOpBuilder().build();
private final long lastReadVersion;
private final DocOpCollector state;
private final DocOpCollector diff;
DocDiff(long lastReadVersion) {
Preconditions.checkArgument(lastReadVersion >= 0, "lastReadVersion = %s", lastReadVersion);
this.lastReadVersion = lastReadVersion;
this.state = new DocOpCollector();
this.diff = new DocOpCollector();
}
void addOperation(String documentId, long version, DocOp docOp) {
if (!IdUtil.isBlipId(documentId) || version < lastReadVersion) {
state.add(docOp);
} else {
diff.add(docOp);
}
}
/**
* @return the state. never null.
*/
DocOp getState() {
DocOp op = state.composeAll();
return op != null ? op : EMPTY_OP;
}
/**
* @return the diff, or null if none
*/
@Nullable DocOp getDiff() {
return diff.composeAll();
}
}
private static final int VERSION_INC = 1;
private final MessageSerializer serializer;
private DocumentFactory<?> docFactory;
/**
* Creates a new serializer based on a concrete implementation of either
* client or server side serializer
*
* @param serializer The concrete implementation of server/client side
* serializer
*/
public WaveSerializer(MessageSerializer serializer) {
this(serializer, WaveletUtil.DEFAULT_DOC_FACTORY);
}
public WaveSerializer(MessageSerializer serializer, DocumentFactory<?> docFactory) {
this.serializer = serializer;
this.docFactory = docFactory;
}
public void setDocFactory(DocumentFactory<?> docFactory) {
this.docFactory = docFactory;
}
public String serializeOperation(WaveletOperation op) {
ProtocolWaveletOperation opMessage = OperationSerializer.createMessage(op);
return serializer.serializeOp(opMessage);
}
public String serializeDelta(WaveletOperation operation) {
Delta delta = MessageFactoryHelper.createDelta();
delta.setAuthor(operation.getContext().getCreator().getAddress());
delta.setTimestampMillis(operation.getContext().getTimestamp());
delta.setOperation(OperationSerializer.createMessage(operation));
return serializer.serializeDelta(delta);
}
public List<String> serializeDeltas(List<WaveletOperation> input) {
ImmutableList.Builder<String> b = ImmutableList.builder();
for (WaveletOperation op : input) {
b.add(serializeDelta(op));
}
return b.build();
}
/**
* The extra parameters are required because they are not present in the
* serialized form of a wavelet operation.
*/
public WaveletOperation deserializeOperation(ProtocolWaveletOperation message,
ParticipantId creator, long timestamp) throws MessageException {
try {
return OperationFactory.createWaveletOperation(
new WaveletOperationContext(creator, timestamp, 1), message);
} catch (InvalidInputException e) {
throw new MessageException(e);
}
}
public WaveletOperation deserializeDelta(Delta in) throws MessageException {
return deserializeOperation(in.getOperation(),
ParticipantId.ofUnsafe(in.getAuthor()), in.getTimestampMillis());
}
public WaveletOperation deserializeDelta(String in) throws MessageException {
return deserializeDelta(serializer.deserializeDelta(in));
}
/**
* Serializes wavelet to JSON string.
*/
public String serializeWavelet(WaveletDataImpl wavelet) {
Preconditions.checkNotNull(wavelet.getCreator(), "Null creator");
return serializer.serializeWavelet(createWaveletMessage(wavelet));
}
/**
* Deserializes wavelet back into WaveletDataImpl.
*
* @param waveletName WaveletName that the deserialized wavelet will have
*/
public WaveletDataImpl deserializeWavelet(WaveletName waveletName, String serializedSnapshot)
throws MessageException {
return createWaveletData(waveletName, serializer.deserializeWavelet(serializedSnapshot));
}
/**
* Returns the serialized wavelet with diffs.
*/
public String serializeWaveletDiff(WaveletDataImpl intermediateWavelet,
WaveletDataImpl currentWavelet, StringMap<Long> lastReadVersions, List<String> mutations) {
return serializer.serializeDiff(createWaveletDiffMessage(
intermediateWavelet, currentWavelet, lastReadVersions, mutations));
}
/**
* Deserializes the serialized wavelet in diff format into instance of
* WaveletDataImpl.
*
* @param waveletName WaveletName of the resulting wavelet
*/
public WaveletDataImpl deserializeWaveletDiff(WaveletName waveletName, String serializedDiff)
throws MessageException {
return createWaveletData(waveletName, serializer.deserializeDiff(serializedDiff));
}
/**
* Serializes OperationBatch to JSON string.
*/
public String serializeOperationBatch(List<WaveletOperation> input) {
Preconditions.checkState(input.size() >= 1, "Operation batch input should have >= 1 items");
OperationBatch batch = MessageFactoryHelper.createOperationBatch();
for (WaveletOperation op : input) {
batch.addOperation(OperationSerializer.createMessage(op));
}
return serializer.serializeOperationBatch(batch);
}
public List<WaveletOperation> deserializeOperationBatch(
ParticipantId author, String serializedOperationBatch,
long timestamp) throws MessageException {
OperationBatch batch = serializer.deserializeOperationBatch(serializedOperationBatch);
List<WaveletOperation> operations = new ArrayList<WaveletOperation>();
try {
WaveletOperationContext context =
new WaveletOperationContext(author, timestamp, VERSION_INC);
for (ProtocolWaveletOperation op : batch.getOperation()) {
operations.add(OperationFactory.createWaveletOperation(context, op));
}
return operations;
} catch (InvalidInputException e) {
throw new MessageException(e);
}
}
/**
* Deserializes the diff part of the serialized wavelet into a map from
* documentid to operation that brings the document from last read state
* to the actual state
*/
public StringMap<DocOp> deserializeDocumentsDiffs(WaveletDiffSnapshot diffSnapshot)
throws MessageException {
StringMap<DocOp> docOps = CollectionUtils.createStringMap();
try {
for (DocumentDiffSnapshot docDiff : diffSnapshot.getDocument()) {
DocOp op;
if (docDiff.getDiff() == null) {
op = null;
} else {
op = OperationFactory.createDocumentOperation(docDiff.getDiff());
}
docOps.put(docDiff.getDocumentId(), op);
}
return docOps;
} catch (InvalidInputException e) {
throw new MessageException(e);
}
}
/**
* Creates wavelet snapshot with diff
*/
public WaveletDiffSnapshot createWaveletDiffMessage(WaveletDataImpl intermediateWavelet,
WaveletDataImpl currentWavelet, StringMap<Long> lastReadVersions, List<String> mutations) {
WaveletDiffSnapshot waveletDiff = MessageFactoryHelper.createWaveletDiffSnapshot();
waveletDiff.setWaveletId(
ModernIdSerialiser.INSTANCE.serialiseWaveletId(currentWavelet.getWaveletId()));
waveletDiff.addAllParticipant(listOfParticipantAddresses(currentWavelet.getParticipants()));
waveletDiff.addAllDocument(getDocumentDiffs(
intermediateWavelet, mutations, lastReadVersions, currentWavelet));
waveletDiff.setVersion(currentWavelet.getVersion());
waveletDiff.setLastModifiedTime(currentWavelet.getLastModifiedTime());
waveletDiff.setCreator(currentWavelet.getCreator().getAddress());
waveletDiff.setCreationTime(currentWavelet.getCreationTime());
return waveletDiff;
}
/**
* Method responsible for creating DocumentDiffSnapshot object out of a
* mutation history of a wavelet and last read version specified in map.
*/
private List<DocumentDiffSnapshot> getDocumentDiffs(WaveletDataImpl intermediateWavelet,
List<String> mutations, StringMap<Long> lastReadVersions, WaveletDataImpl headWavelet) {
try {
StringMap<DocDiff> documentDiffMap =
createDocumentDiffMap(intermediateWavelet, mutations, lastReadVersions);
return createDocumentDiffList(documentDiffMap, headWavelet);
} catch (InvalidInputException e) {
throw new RuntimeException(e);
} catch (MessageException e) {
throw new RuntimeException(e);
}
}
/**
* Creates a map that maps documentId's to objects representing the state of
* the document up to the last read version (specified in map) as well as the
* differences that were made to document after last read version.
*/
private StringMap<DocDiff> createDocumentDiffMap(
WaveletDataImpl intermediateWavelet, List<String> tailMutations,
StringMap<Long> lastReadVersions)
throws MessageException, InvalidInputException {
StringMap<DocDiff> documentDiffMap = CollectionUtils.createStringMap();
WaveletId waveletId = intermediateWavelet.getWaveletId();
long intermediateVersion = intermediateWavelet.getVersion();
for (String documentId : intermediateWavelet.getDocumentIds()) {
Long lastReadVersion = lastReadVersions.get(documentId, 0L);
BlipDataImpl document = intermediateWavelet.getDocument(documentId);
DocDiff docDiff = new DocDiff(lastReadVersion);
Preconditions.checkArgument(lastReadVersion >= intermediateVersion
|| lastReadVersion == 0 || lastReadVersion >= document.getLastModifiedVersion(),
"intermediate wavelet %s is newer (@%s) than last read version %s of doc %s",
waveletId, intermediateVersion, lastReadVersion, documentId);
DocOp state = document.getContent().asOperation();
docDiff.addOperation(documentId, 0, state);
documentDiffMap.put(documentId, docDiff);
}
long version = intermediateVersion;
for (String mutation : tailMutations) {
ProtocolWaveletOperation op = serializer.deserializeDelta(mutation).getOperation();
if (op.hasMutateDocument()) {
MutateDocument mutateDocument = op.getMutateDocument();
String documentId = mutateDocument.getDocumentId();
DocDiff docDiff = documentDiffMap.get(documentId);
if (docDiff == null) {
docDiff = new DocDiff(lastReadVersions.get(documentId, 0L));
documentDiffMap.put(documentId, docDiff);
}
long lastReadVersion = lastReadVersions.get(documentId, -1L);
docDiff.addOperation(mutateDocument.getDocumentId(), version,
OperationFactory.createDocumentOperation(mutateDocument.getDocumentOperation()));
}
version++;
}
return documentDiffMap;
}
/**
* Creates a list of objects representing snapshot of documents in diff format
* from the previously created map of documents to DocDiffs.
*/
private List<DocumentDiffSnapshot> createDocumentDiffList(
StringMap<DocDiff> diffSnapshotMap, final WaveletDataImpl headWavelet) {
final List<DocumentDiffSnapshot> result = new ArrayList<DocumentDiffSnapshot>();
diffSnapshotMap.each(new ProcV<DocDiff>() {
@Override
public void apply(String documentId, DocDiff diffState) {
BlipDataImpl document = headWavelet.getDocument(documentId);
if (document != null) {
DocumentDiffSnapshot docDiff = MessageFactoryHelper.createDocumentDiffSnapshot();
docDiff.setDocumentId(documentId);
docDiff.setAuthor(document.getAuthor().getAddress());
docDiff.addAllContributor(listOfParticipantAddresses(document.getContributors()));
// TODO(piotrkaleta): Add contributor diffs once Walkaround supports
// them
docDiff.addAllAddedContributor(Collections.<String> emptyList());
docDiff.addAllRemovedContributor(Collections.<String> emptyList());
docDiff.setLastModifiedVersion(document.getLastModifiedVersion());
docDiff.setLastModifiedTime(document.getLastModifiedTime());
docDiff.setState(OperationSerializer.createMutationOp(diffState.getState()));
DocOp diffOp = diffState.getDiff();
if (diffOp != null) {
docDiff.setDiff(OperationSerializer.createMutationOp(diffOp));
}
result.add(docDiff);
}
}
});
return result;
}
/**
* First stage of serialization - creates a Protobuf Message class instance
* from wavelet.
*/
public WalkaroundWaveletSnapshot createWaveletMessage(WaveletDataImpl waveletData) {
WalkaroundWaveletSnapshot wavelet = MessageFactoryHelper.createWaveletSnapshot();
wavelet.setVersion(waveletData.getVersion());
wavelet.setCreator(waveletData.getCreator().getAddress());
wavelet.setCreationTime(waveletData.getCreationTime());
wavelet.setLastModifiedTime(waveletData.getLastModifiedTime());
wavelet.addAllDocument(listOfDocuments(waveletData));
wavelet.addAllParticipant(listOfParticipantAddresses(waveletData.getParticipants()));
return wavelet;
}
/**
* Retrieves list of documents in a wavelet.
*/
private List<WalkaroundDocumentSnapshot> listOfDocuments(WaveletDataImpl wavelet) {
List<WalkaroundDocumentSnapshot> documents = new ArrayList<WalkaroundDocumentSnapshot>();
for (String name : wavelet.getDocumentIds()) {
BlipDataImpl blip = wavelet.getDocument(name);
documents.add(toProtoBuf(blip));
}
return documents;
}
/**
* Serializes blip into Message.
*/
private WalkaroundDocumentSnapshot toProtoBuf(BlipDataImpl blip) {
WalkaroundDocumentSnapshot document = MessageFactoryHelper.createDocumentSnapshot();
document.setDocumentId(blip.getId());
document.setAuthor(blip.getAuthor().getAddress());
document.setLastModifiedTime(blip.getLastModifiedTime());
document.setLastModifiedVersion(blip.getLastModifiedVersion());
document.addAllContributor(listOfParticipantAddresses(blip.getContributors()));
ProtocolDocumentOperation documentOperation =
OperationSerializer.createMutationOp(blip.getContent().asOperation());
document.setContent(documentOperation);
return document;
}
/**
* Turns set of participant addresses into list of string-serialized addresses.
*
* @param participantIds Set of ids of participants
* @return list of serialized addresses
*/
private List<String> listOfParticipantAddresses(Set<ParticipantId> participantIds) {
List<String> participants = new ArrayList<String>();
for (ParticipantId id : participantIds) {
participants.add(id.getAddress());
}
return participants;
}
private void addParticipants(WaveletDataImpl wavelet, List<String> addresses)
throws InvalidParticipantAddress {
for (String address : addresses) {
wavelet.addParticipant(ParticipantId.of(address));
}
}
/**
* Turns list of serialized participant addresses back into deserialized
* ParticipantId's
*/
private List<ParticipantId> listOfParticipants(List<String> addresses)
throws InvalidParticipantAddress {
List<ParticipantId> participants = new ArrayList<ParticipantId>();
for (String address : addresses) {
participants.add(ParticipantId.of(address));
}
return participants;
}
// TODO(piotrkaleta): There's a lot of duplicated code down there. This is
// because we use diff format for conversational wavelets, whereas non-diff
// format for user data wavelets. The best way to fix it is to make udw's also
// use diff format with the diff field always set to null.
/**
* Deserializes documents from list and adds them to wavelet.
*
* @param wavelet Wavelet to add deserialized documents to
* @param documents Docs to deserialize and add
*/
private void addDocuments(
WaveletDataImpl wavelet, List<? extends WalkaroundDocumentSnapshot> documents)
throws InvalidParticipantAddress, InvalidInputException {
for (WalkaroundDocumentSnapshot document : documents) {
String docId = document.getDocumentId();
ParticipantId author = ParticipantId.of(document.getAuthor());
List<ParticipantId> contributors = listOfParticipants(document.getContributor());
DocInitialization content =
OperationFactory.createDocumentInitialization(document.getContent());
long docLastModifiedTime = (long) document.getLastModifiedTime();
long lastModifiedVersion = (long) document.getLastModifiedVersion();
wavelet.createDocument(
docId, author, contributors, content, docLastModifiedTime, lastModifiedVersion);
}
}
/**
* Deserializes documents from list and adds them to wavelet in diff format.
*
* @param wavelet Wavelet to add deserialized documents to
* @param documents Docs to deserialize and add
*/
private void addDiffDocuments(
WaveletDataImpl wavelet, List<? extends DocumentDiffSnapshot> documents)
throws InvalidParticipantAddress, InvalidInputException {
for (DocumentDiffSnapshot document : documents) {
String docId = document.getDocumentId();
ParticipantId author = ParticipantId.of(document.getAuthor());
List<ParticipantId> contributors = listOfParticipants(document.getContributor());
DocInitialization content =
OperationFactory.createDocumentInitialization(document.getState());
long docLastModifiedTime = (long) document.getLastModifiedTime();
long lastModifiedVersion = (long) document.getLastModifiedVersion();
wavelet.createDocument(
docId, author, contributors, content, docLastModifiedTime, lastModifiedVersion);
}
}
/**
* Deserializes protobuf message representing wavelet and turns it into
* WaveletDataImpl object.
*
* @param waveletName WaveletName that the wavelet will have
*/
public WaveletDataImpl createWaveletData(
WaveletName waveletName, WalkaroundWaveletSnapshot waveletMessage)
throws MessageException {
try {
ParticipantId creator = ParticipantId.of(waveletMessage.getCreator());
long creationTime = (long) waveletMessage.getCreationTime();
long lastModifiedTime = (long) waveletMessage.getLastModifiedTime();
HashedVersion hashedVersion = HashedVersion.unsigned(0);
long version = (long) waveletMessage.getVersion();
WaveletDataImpl wavelet =
new WaveletDataImpl(waveletName.waveletId, creator, creationTime, version, hashedVersion,
lastModifiedTime, waveletName.waveId, docFactory);
addParticipants(wavelet, waveletMessage.getParticipant());
addDocuments(wavelet, waveletMessage.getDocument());
return wavelet;
} catch (InvalidParticipantAddress e) {
throw new MessageException("Invalid participant address", e);
} catch (InvalidInputException e) {
throw new MessageException("Invalid input", e);
}
}
/**
* Deserializes protobuf message representing wavelet in diff format and turns
* it into WaveletDataImpl object.
*
* @param waveletName WaveletName that the wavelet will have
*/
public WaveletDataImpl createWaveletData(
WaveletName waveletName, WaveletDiffSnapshot waveletMessage)
throws MessageException {
try {
ParticipantId creator = ParticipantId.of(waveletMessage.getCreator());
long creationTime = (long) waveletMessage.getCreationTime();
long lastModifiedTime = (long) waveletMessage.getLastModifiedTime();
HashedVersion hashedVersion = HashedVersion.unsigned(0);
long version = (long) waveletMessage.getVersion();
WaveletDataImpl wavelet =
new WaveletDataImpl(waveletName.waveletId, creator, creationTime, version, hashedVersion,
lastModifiedTime, waveletName.waveId, docFactory);
addParticipants(wavelet, waveletMessage.getParticipant());
addDiffDocuments(wavelet, waveletMessage.getDocument());
return wavelet;
} catch (InvalidParticipantAddress e) {
throw new MessageException("Invalid participant address", e);
} catch (InvalidInputException e) {
throw new MessageException("Invalid input", 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.wave.shared;
/**
* Used to explicitly mark locations where wave versions (longs) are converted
* to object store versions (ints).
*
* @author danilatos@google.com (Daniel Danilatos)
*/
// TODO(danilatos): This is no longer necessary, let's make everything long
// (or maybe double on the client) and get rid of this.
public final class Versions {
public static int truncate(long version) {
if (version > Integer.MAX_VALUE) {
throw new AssertionError("huge version " + version);
}
return (int) 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.wave.shared;
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 org.waveprotocol.wave.model.document.operation.AnnotationBoundaryMap;
import org.waveprotocol.wave.model.document.operation.Attributes;
import org.waveprotocol.wave.model.document.operation.AttributesUpdate;
import org.waveprotocol.wave.model.document.operation.DocOp;
import org.waveprotocol.wave.model.document.operation.DocOpCursor;
import org.waveprotocol.wave.model.operation.wave.AddParticipant;
import org.waveprotocol.wave.model.operation.wave.BlipContentOperation;
import org.waveprotocol.wave.model.operation.wave.BlipOperationVisitor;
import org.waveprotocol.wave.model.operation.wave.NoOp;
import org.waveprotocol.wave.model.operation.wave.RemoveParticipant;
import org.waveprotocol.wave.model.operation.wave.SubmitBlip;
import org.waveprotocol.wave.model.operation.wave.VersionUpdateOp;
import org.waveprotocol.wave.model.operation.wave.WaveletBlipOperation;
import org.waveprotocol.wave.model.operation.wave.WaveletOperation;
import org.waveprotocol.wave.model.operation.wave.WaveletOperationVisitor;
import java.util.Map;
/**
* A class for serializing operations.
*
* @author Alexandre Mah
*/
public class OperationSerializer {
/**
* A class that holds a single message that has been converted from a DocumentOperation.
*/
private static class Visitor implements WaveletOperationVisitor, BlipOperationVisitor {
private final ProtocolWaveletOperation message = MessageFactoryHelper.createWaveOp();
private String blipId;
@Override
public void visitWaveletBlipOperation(WaveletBlipOperation op) {
blipId = op.getBlipId();
op.getBlipOp().acceptVisitor(this);
blipId = null;
}
@Override
public void visitBlipContentOperation(BlipContentOperation op) {
DocOp mutationOp = op.getContentOp();
message.setMutateDocument(createMutateDocumentMessage(blipId, mutationOp));
}
@Override
public void visitAddParticipant(AddParticipant op) {
message.setAddParticipant(op.getParticipantId().getAddress());
}
@Override
public void visitNoOp(NoOp op) {
message.setNoOp(true);
}
@Override
public void visitVersionUpdateOp(VersionUpdateOp op) {
// Not serialisable
}
@Override
public void visitRemoveParticipant(RemoveParticipant op) {
message.setRemoveParticipant(op.getParticipantId().getAddress());
}
@Override
public void visitSubmitBlip(SubmitBlip op) {
// NOTE(piotrkaleta): Not existing anymore
}
/**
* @return The message representing the written operation.
*/
ProtocolWaveletOperation getMessage() {
return message;
}
}
/**
* Converts an operation to a message.
*
* @param operation The operation to convert.
* @return The message representing the operation.
*/
public static ProtocolWaveletOperation createMessage(WaveletOperation operation) {
Visitor visitor = new Visitor();
operation.acceptVisitor(visitor);
return visitor.getMessage();
}
private static KeyValuePair createKeyValuePair(String key, String value) {
KeyValuePair attribute = MessageFactoryHelper.createDocumentKeyValuePair();
attribute.setKey(key);
if (value != null) {
attribute.setValue(value);
}
return attribute;
}
private static KeyValueUpdate createKeyValueUpdate(
String key, String oldValue, String newValue) {
KeyValueUpdate attribute = MessageFactoryHelper.createDocumentKeyValueUpdate();
attribute.setKey(key);
if (oldValue != null) {
attribute.setOldValue(oldValue);
}
if (newValue != null) {
attribute.setNewValue(newValue);
}
return attribute;
}
private static ElementStart createElementStart(String type, Attributes attrs) {
ElementStart elementStart = MessageFactoryHelper.createDocumentElementStart();
elementStart.setType(type);
for (Map.Entry<String, String> attribute : attrs.entrySet()) {
elementStart.addAttribute(
createKeyValuePair(attribute.getKey(), attribute.getValue()));
}
return elementStart;
}
/**
* Convert the given document mutation op into a message.
*
* @param blipId
* @param mutationOp
* @return MutateDocument
*/
public static MutateDocument createMutateDocumentMessage(String blipId, DocOp mutationOp) {
final ProtocolDocumentOperation mutation = createMutationOp(mutationOp);
MutateDocument operation = MessageFactoryHelper.createBlipContentMutation();
operation.setDocumentId(blipId);
operation.setDocumentOperation(mutation);
return operation;
}
/**
* Convert the given document mutation op into a mutation op message
* @param docOp
* @return DocumentMutation
*/
public static ProtocolDocumentOperation createMutationOp(DocOp docOp) {
final ProtocolDocumentOperation mutation =
MessageFactoryHelper.createDocumentOperation();
docOp.apply(new DocOpCursor() {
@Override
public void retain(int itemCount) {
Component component = MessageFactoryHelper.createDocumentOperationComponent();
component.setRetainItemCount(itemCount);
mutation.addComponent(component);
}
@Override
public void characters(String characters) {
Component component = MessageFactoryHelper.createDocumentOperationComponent();
component.setCharacters(characters);
mutation.addComponent(component);
}
@Override
public void elementStart(String type, Attributes attributes) {
Component component = MessageFactoryHelper.createDocumentOperationComponent();
component.setElementStart(createElementStart(type, attributes));
mutation.addComponent(component);
}
@Override
public void elementEnd() {
Component component = MessageFactoryHelper.createDocumentOperationComponent();
component.setElementEnd(true);
mutation.addComponent(component);
}
@Override
public void deleteCharacters(String characters) {
Component component = MessageFactoryHelper.createDocumentOperationComponent();
component.setDeleteCharacters(characters);
mutation.addComponent(component);
}
@Override
public void deleteElementStart(String type, Attributes attributes) {
Component component = MessageFactoryHelper.createDocumentOperationComponent();
component.setDeleteElementStart(createElementStart(type, attributes));
mutation.addComponent(component);
}
@Override
public void deleteElementEnd() {
Component component = MessageFactoryHelper.createDocumentOperationComponent();
component.setDeleteElementEnd(true);
mutation.addComponent(component);
}
@Override
public void replaceAttributes(Attributes oldAttributes, Attributes newAttributes) {
Component component =
MessageFactoryHelper.createDocumentOperationComponent();
ReplaceAttributes replace =
MessageFactoryHelper.createDocumentReplaceAttributes();
if (oldAttributes.isEmpty() && newAttributes.isEmpty()) {
replace.setEmpty(true);
} else {
for (Map.Entry<String, String> e : oldAttributes.entrySet()) {
replace.addOldAttribute(createKeyValuePair(e.getKey(), e.getValue()));
}
for (Map.Entry<String, String> e : newAttributes.entrySet()) {
replace.addNewAttribute(createKeyValuePair(e.getKey(), e.getValue()));
}
}
component.setReplaceAttributes(replace);
mutation.addComponent(component);
}
@Override
public void updateAttributes(AttributesUpdate update) {
Component component = MessageFactoryHelper.createDocumentOperationComponent();
UpdateAttributes updateAttributes =
MessageFactoryHelper.createDocumentUpdateAttributes();
int n = update.changeSize();
if (n == 0) {
updateAttributes.setEmpty(true);
} else {
for (int i = 0; i < n; i++) {
updateAttributes.addAttributeUpdate(createKeyValueUpdate(
update.getChangeKey(i), update.getOldValue(i), update.getNewValue(i)));
}
}
component.setUpdateAttributes(updateAttributes);
mutation.addComponent(component);
}
@Override
public void annotationBoundary(AnnotationBoundaryMap map) {
Component component = MessageFactoryHelper.createDocumentOperationComponent();
AnnotationBoundary boundary =
MessageFactoryHelper.createDocumentAnnotationBoundary();
int endSize = map.endSize();
int changeSize = map.changeSize();
if (endSize == 0 && changeSize == 0) {
boundary.setEmpty(true);
} else {
for (int i = 0; i < endSize; i++) {
boundary.addEnd(map.getEndKey(i));
}
for (int i = 0; i < changeSize; i++) {
boundary.addChange(createKeyValueUpdate(map.getChangeKey(i),
map.getOldValue(i), map.getNewValue(i)));
}
}
component.setAnnotationBoundary(boundary);
mutation.addComponent(component);
}
});
return mutation;
}
}
| 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.shared;
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;
/**
* A factory for creating message objects.
*
* @author zdwang@google.com (David Wang)
*/
public abstract class MessageFactoryHelper {
/**
* The delegate factory.
*/
protected static MessageFactory factory = null;
public static OperationBatch createOperationBatch() {
return factory.createOperationBatch();
}
public static WaveletDiffSnapshot createWaveletDiffSnapshot() {
return factory.createWaveletDiffSnapshot();
}
public static DocumentDiffSnapshot createDocumentDiffSnapshot() {
return factory.createDocumentDiffSnapshot();
}
public static ProtocolWaveletOperation createWaveOp() {
return factory.createWaveOp();
}
public static KeyValuePair createDocumentKeyValuePair() {
return factory.createDocumentKeyValuePair();
}
public static KeyValueUpdate createDocumentKeyValueUpdate() {
return factory.createDocumentKeyValueUpdate();
}
public static ElementStart createDocumentElementStart() {
return factory.createDocumentElementStart();
}
public static ReplaceAttributes createDocumentReplaceAttributes() {
return factory.createDocumentReplaceAttributes();
}
public static UpdateAttributes createDocumentUpdateAttributes() {
return factory.createDocumentUpdateAttributes();
}
public static AnnotationBoundary createDocumentAnnotationBoundary() {
return factory.createDocumentAnnotationBoundary();
}
public static Component createDocumentOperationComponent() {
return factory.createDocumentOperationComponent();
}
public static ProtocolDocumentOperation createDocumentOperation() {
return factory.createDocumentOperation();
}
public static MutateDocument createBlipContentMutation() {
return factory.createMutateDocument();
}
/**
* Gets the factory singleton.
*
* @return the global factory.
*/
public static MessageFactory getFactory() {
return factory;
}
/**
* Sets the factory singleton
*
* @param f the global factory to use.
*/
public static void setFactory(MessageFactory f) {
factory = f;
}
public static WalkaroundWaveletSnapshot createWaveletSnapshot() {
return factory.createWaveletSnapshot();
}
public static WalkaroundDocumentSnapshot createDocumentSnapshot() {
return factory.createDocumentSnapshot();
}
public static Delta createDelta() {
return factory.createDelta();
}
}
| 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.shared;
import com.google.common.base.Preconditions;
import org.waveprotocol.wave.model.document.operation.automaton.DocumentSchema;
import org.waveprotocol.wave.model.id.WaveletId;
import org.waveprotocol.wave.model.id.WaveletName;
import org.waveprotocol.wave.model.operation.OperationException;
import org.waveprotocol.wave.model.operation.wave.WaveletOperation;
import org.waveprotocol.wave.model.schema.SchemaProvider;
import org.waveprotocol.wave.model.version.HashedVersion;
import org.waveprotocol.wave.model.wave.ParticipantId;
import org.waveprotocol.wave.model.wave.data.DocumentFactory;
import org.waveprotocol.wave.model.wave.data.IndexedDocumentFactory;
import org.waveprotocol.wave.model.wave.data.impl.WaveletDataImpl;
import java.util.List;
/**
* Utility class for building wavelets, applying deltas to existing wavelet
* snapshots, etc.
*
* @author piotrkaleta@google.com (Piotr Kaleta)
* @author ohler@google.com (Christian Ohler)
*/
public class WaveletUtil {
public static final DocumentFactory<?> DEFAULT_DOC_FACTORY =
new IndexedDocumentFactory(new SchemaProvider() {
@Override
public DocumentSchema getSchemaForId(WaveletId waveletId, String documentId) {
return DocumentSchema.NO_SCHEMA_CONSTRAINTS;
}
});
public static WaveletDataImpl buildWaveletFromInitialOps(WaveletName waveletName,
List<WaveletOperation> ops, DocumentFactory<?> docFactory) throws OperationException {
Preconditions.checkArgument(!ops.isEmpty(), "Empty list of ops");
WaveletDataImpl wavelet = newWaveletFromInitialOp(waveletName, ops.get(0), docFactory);
applyOps(wavelet, ops);
return wavelet;
}
public static WaveletDataImpl buildWaveletFromInitialOps(WaveletName waveletName,
List<WaveletOperation> ops) throws OperationException {
return buildWaveletFromInitialOps(waveletName, ops, DEFAULT_DOC_FACTORY);
}
private static WaveletDataImpl newWaveletFromInitialOp(
WaveletName waveletName, WaveletOperation initialOp, DocumentFactory<?> docFactory) {
ParticipantId creator = initialOp.getContext().getCreator();
Preconditions.checkNotNull(creator, "Null creator");
long createTime = initialOp.getContext().getTimestamp();
return new WaveletDataImpl(waveletName.waveletId, creator, createTime,
0, HashedVersion.unsigned(0),
createTime, waveletName.waveId, docFactory);
}
public static void applyOps(WaveletDataImpl wavelet, List<WaveletOperation> ops)
throws OperationException {
for (int i = 0; i < ops.size(); i++) {
ops.get(i).apply(wavelet);
}
}
}
| 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.shared;
/**
* Shared constants between server and client.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class SharedConstants {
/**
* Prefix added to data returned from XHRs to guard against XSSI attacks.
*
* See http://google-gruyere.appspot.com/part4
*/
public static final String XSSI_PREFIX = "])}while(1);</x>//";
public static final String UNKNOWN_AVATAR_URL = "/static/images/unknown.jpg";
/**
* Request parameter keys for referencing various values.
*/
public static class Params {
private Params() {}
/** SignedObjectSession protobuf. */
public static final String SESSION = "session";
/** Object version. */
public static final String REVISION = "version";
/** Start version in a range (inclusive). */
public static final String START_REVISION = "start";
/** End version in a range (exclusive). */
public static final String END_REVISION = "end";
}
/** Service names. */
public static class Services {
private Services() {}
public static final String CHANNEL = "channel";
public static final String CONNECT = "connect";
public static final String HISTORY = "history";
public static final String SUBMIT_DELTA = "submitdelta";
}
}
| 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.shared;
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 org.waveprotocol.wave.model.document.operation.AnnotationBoundaryMap;
import org.waveprotocol.wave.model.document.operation.Attributes;
import org.waveprotocol.wave.model.document.operation.AttributesUpdate;
import org.waveprotocol.wave.model.document.operation.DocOp;
import org.waveprotocol.wave.model.document.operation.DocOpComponentType;
import org.waveprotocol.wave.model.document.operation.DocOpCursor;
import org.waveprotocol.wave.model.document.operation.impl.AnnotationBoundaryMapImpl;
import org.waveprotocol.wave.model.document.operation.impl.AttributesImpl;
import org.waveprotocol.wave.model.document.operation.impl.AttributesUpdateImpl;
import org.waveprotocol.wave.model.document.operation.impl.DocOpUtil;
import org.waveprotocol.wave.model.document.operation.util.ImmutableStateMap.Attribute;
import org.waveprotocol.wave.model.document.operation.util.ImmutableUpdateMap.AttributeUpdate;
import org.waveprotocol.wave.model.document.util.DocOpScrub;
import java.util.ArrayList;
import java.util.List;
/**
* Thin wrapper over DocumentOperation to provide a DocOp interface. This is
* particularly important for efficiency. Especially on the client.
*
* Note, this class is purposely unchecked for speed.
*
* @author zdwang@google.com (David Wang)
*/
class MessageWrapperDocOp implements DocOp {
/**
* A provider which returns the ProtocolDocumentOperation to be used.
*
* @author reuben@google.com (Reuben Kan)
*/
interface DocOpMessageProvider {
ProtocolDocumentOperation getContent();
}
/**
* Thrown by accessors on MessageWrapperDocOps when they detect that the
* underlying data is invalid. Since MessageWrapperDocOp does not check the
* validity of its underlying data on construction (for efficiency), and the
* DocOp interface assumes valid data and thus does not declare any checked
* exceptions, this is a RuntimeException.
*/
public static class DelayedInvalidInputException extends RuntimeException {
private static final long serialVersionUID = 370273955957838556L;
public DelayedInvalidInputException(String message) {
super(message);
}
public DelayedInvalidInputException(Throwable cause) {
super(cause);
}
public DelayedInvalidInputException(String message, Throwable cause) {
super(message, cause);
}
}
private final DocOpMessageProvider provider;
private final boolean checkAttributes;
/**
* @param provider The provider of the message to wrap
* @param checkAttributes If the attributes should be checked when you use this object.
*/
public MessageWrapperDocOp(DocOpMessageProvider provider, boolean checkAttributes) {
this.provider = provider;
this.checkAttributes = checkAttributes;
}
@Override
public void applyComponent(int i, DocOpCursor cursor) {
Component component = provider.getContent().getComponent(i);
applyComponent(cursor, component);
}
@Override
public AnnotationBoundaryMap getAnnotationBoundary(int i) {
Component component = provider.getContent().getComponent(i);
return annotationBoundaryFrom(component.getAnnotationBoundary());
}
@Override
public String getCharactersString(int i) {
Component component = provider.getContent().getComponent(i);
return component.getCharacters();
}
@Override
public String getDeleteCharactersString(int i) {
Component component = provider.getContent().getComponent(i);
return component.getDeleteCharacters();
}
@Override
public Attributes getDeleteElementStartAttributes(int i) {
Component component = provider.getContent().getComponent(i);
ElementStart elementStart = component.getDeleteElementStart();
return attributesFrom(elementStart);
}
@Override
public String getDeleteElementStartTag(int i) {
Component component = provider.getContent().getComponent(i);
ElementStart elementStart = component.getDeleteElementStart();
return elementStart.getType();
}
@Override
public Attributes getElementStartAttributes(int i) {
Component component = provider.getContent().getComponent(i);
ElementStart elementStart = component.getElementStart();
return attributesFrom(elementStart);
}
@Override
public String getElementStartTag(int i) {
Component component = provider.getContent().getComponent(i);
ElementStart elementStart = component.getElementStart();
return elementStart.getType();
}
@Override
public Attributes getReplaceAttributesNewAttributes(int i) {
Component component = provider.getContent().getComponent(i);
ReplaceAttributes r = component.getReplaceAttributes();
return newAttributesFrom(r);
}
@Override
public Attributes getReplaceAttributesOldAttributes(int i) {
Component component = provider.getContent().getComponent(i);
ReplaceAttributes r = component.getReplaceAttributes();
return oldAttributesFrom(r);
}
@Override
public int getRetainItemCount(int i) {
Component component = provider.getContent().getComponent(i);
return component.getRetainItemCount();
}
@Override
public DocOpComponentType getType(int i) {
Component component = provider.getContent().getComponent(i);
return getType(component);
}
@Override
public AttributesUpdate getUpdateAttributesUpdate(int i) {
Component component = provider.getContent().getComponent(i);
UpdateAttributes r = component.getUpdateAttributes();
return attributesUpdateFrom(r);
}
@Override
public int size() {
return provider.getContent().getComponentSize();
}
@Override
public void apply(DocOpCursor cursor) {
for (int i = 0; i < provider.getContent().getComponentSize(); ++i) {
Component component = provider.getContent().getComponent(i);
applyComponent(cursor, component);
}
}
/**
* Gets the DocOpComponentType of the ProtocolDocumentOperation.Component.
*/
private DocOpComponentType getType(ProtocolDocumentOperation.Component component) {
// This if/elseif chain is not ideal; I'm sorting it by expected frequency.
// TODO(ohler): Find out if this if/elseif chain is slow.
if (component.hasRetainItemCount()) {
return DocOpComponentType.RETAIN;
} else if (component.hasAnnotationBoundary()) {
return DocOpComponentType.ANNOTATION_BOUNDARY;
} else if (component.hasCharacters()) {
return DocOpComponentType.CHARACTERS;
} else if (component.hasDeleteCharacters()) {
return DocOpComponentType.DELETE_CHARACTERS;
} else if (component.hasElementStart()) {
return DocOpComponentType.ELEMENT_START;
} else if (component.hasElementEnd()) {
return DocOpComponentType.ELEMENT_END;
} else if (component.hasDeleteElementStart()) {
return DocOpComponentType.DELETE_ELEMENT_START;
} else if (component.hasDeleteElementEnd()) {
return DocOpComponentType.DELETE_ELEMENT_END;
} else if (component.hasReplaceAttributes()) {
return DocOpComponentType.REPLACE_ATTRIBUTES;
} else if (component.hasUpdateAttributes()) {
return DocOpComponentType.UPDATE_ATTRIBUTES;
} else {
throw new DelayedInvalidInputException("Fell through in getType: " + provider.getContent());
}
}
/**
* Applies a single component to the cursor.
*/
private void applyComponent(DocOpCursor cursor, Component component) {
// This if/elseif chain is not ideal; I'm sorting it by expected frequency.
// TODO(ohler): Find out if this if/elseif chain is slow.
if (component.hasRetainItemCount()) {
cursor.retain(component.getRetainItemCount());
} else if (component.hasAnnotationBoundary()) {
cursor.annotationBoundary(annotationBoundaryFrom(component.getAnnotationBoundary()));
} else if (component.hasCharacters()) {
cursor.characters(component.getCharacters());
} else if (component.hasDeleteCharacters()) {
cursor.deleteCharacters(component.getDeleteCharacters());
} else if (component.hasElementStart()) {
ElementStart elementStart = component.getElementStart();
cursor.elementStart(elementStart.getType(), attributesFrom(elementStart));
} else if (component.hasElementEnd()) {
if (!component.getElementEnd()) {
throw new DelayedInvalidInputException("Element end present but false: " +
provider.getContent());
}
cursor.elementEnd();
} else if (component.hasDeleteElementStart()) {
ElementStart elementStart = component.getDeleteElementStart();
cursor.deleteElementStart(elementStart.getType(), attributesFrom(elementStart));
} else if (component.hasDeleteElementEnd()) {
if (!component.getDeleteElementEnd()) {
throw new DelayedInvalidInputException("Delete element end present but false: " + provider);
}
cursor.deleteElementEnd();
} else if (component.hasReplaceAttributes()) {
ReplaceAttributes r = component.getReplaceAttributes();
cursor.replaceAttributes(oldAttributesFrom(r), newAttributesFrom(r));
} else if (component.hasUpdateAttributes()) {
UpdateAttributes r = component.getUpdateAttributes();
cursor.updateAttributes(attributesUpdateFrom(r));
} else {
throw new DelayedInvalidInputException("Fell through in applyComponent: " + provider);
}
}
private Attributes createAttributesImpl(List<Attribute> sortedAttributes) {
try {
if (checkAttributes) {
return AttributesImpl.fromSortedAttributes(sortedAttributes);
} else {
return AttributesImpl.fromSortedAttributesUnchecked(sortedAttributes);
}
} catch (IllegalArgumentException e) {
throw new DelayedInvalidInputException("Invalid attributes: " + e, e);
}
}
private AttributesUpdate createAttributesUpdateImpl(List<AttributeUpdate> sortedUpdates) {
try {
if (checkAttributes) {
return AttributesUpdateImpl.fromSortedUpdates(sortedUpdates);
} else {
return AttributesUpdateImpl.fromSortedUpdatesUnchecked(sortedUpdates);
}
} catch (IllegalArgumentException e) {
throw new DelayedInvalidInputException("Invalid attributes update: " + e, e);
}
}
private Attributes attributesFrom(ElementStart message) {
List<Attribute> attributes = new ArrayList<Attribute>();
for (int i = 0; i < message.getAttributeSize(); i++) {
KeyValuePair p = message.getAttribute(i);
attributes.add(new Attribute(p.getKey(), p.getValue()));
}
return createAttributesImpl(attributes);
}
private Attributes oldAttributesFrom(ReplaceAttributes message) {
List<Attribute> attributes = new ArrayList<Attribute>();
for (int i = 0; i < message.getOldAttributeSize(); i++) {
KeyValuePair p = message.getOldAttribute(i);
attributes.add(new Attribute(p.getKey(), p.getValue()));
}
return createAttributesImpl(attributes);
}
private Attributes newAttributesFrom(ReplaceAttributes message) {
List<Attribute> attributes = new ArrayList<Attribute>();
for (int i = 0; i < message.getNewAttributeSize(); i++) {
KeyValuePair p = message.getNewAttribute(i);
attributes.add(new Attribute(p.getKey(), p.getValue()));
}
return createAttributesImpl(attributes);
}
private AttributesUpdate attributesUpdateFrom(UpdateAttributes message) {
List<AttributeUpdate> updates = new ArrayList<AttributeUpdate>();
for (int i = 0; i < message.getAttributeUpdateSize(); i++) {
KeyValueUpdate p = message.getAttributeUpdate(i);
updates.add(new AttributeUpdate(p.getKey(), p.hasOldValue() ? p.getOldValue() : null,
p.hasNewValue() ? p.getNewValue() : null));
}
return createAttributesUpdateImpl(updates);
}
private static AnnotationBoundaryMap annotationBoundaryFrom(AnnotationBoundary message) {
String[] endKeys = new String[message.getEndSize()];
String[] changeKeys = new String[message.getChangeSize()];
String[] changeOldValues = new String[message.getChangeSize()];
String[] changeNewValues = new String[message.getChangeSize()];
for (int i = 0; i < endKeys.length; i++) {
endKeys[i] = message.getEnd(i);
}
for (int i = 0; i < changeKeys.length; i++) {
KeyValueUpdate change = message.getChange(i);
changeKeys[i] = change.getKey();
changeOldValues[i] = change.hasOldValue() ? change.getOldValue() : null;
changeNewValues[i] = change.hasNewValue() ? change.getNewValue() : null;
}
try {
return AnnotationBoundaryMapImpl.builder()
.initializationEnd(endKeys)
.updateValues(changeKeys, changeOldValues, changeNewValues)
.build();
} catch (IllegalArgumentException e) {
throw new DelayedInvalidInputException("Invalid annotation boundary: " + e, e);
}
}
@Override
public String toString() {
return "MessageBased@" + Integer.toHexString(System.identityHashCode(this)) + "[" +
DocOpUtil.toConciseString(DocOpScrub.maybeScrub(this)) + "]";
}
}
| 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.server.wavemanager;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.tools.mapreduce.AppEngineMapper;
import com.google.inject.Inject;
import com.google.walkaround.proto.ObsoleteWaveletMetadata;
import com.google.walkaround.proto.gson.ObsoleteWaveletMetadataGsonImpl;
import com.google.walkaround.slob.server.GsonProto;
import com.google.walkaround.slob.server.MutationLog;
import com.google.walkaround.slob.server.SlobFacilities;
import com.google.walkaround.slob.shared.MessageException;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.slob.shared.StateAndVersion;
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.wave.server.GuiceSetup;
import com.google.walkaround.wave.server.conv.ConvStore;
import com.google.walkaround.wave.server.model.WaveObjectStoreModel.ReadableWaveletObject;
import org.apache.hadoop.io.NullWritable;
import java.io.IOException;
import java.util.logging.Logger;
/**
* Mapreduce mapper that re-indexes and re-extracts ACL metadata from all
* conversations.
*
* @author ohler@google.com (Christian Ohler)
*/
public class ReIndexMapper extends AppEngineMapper<Key, Entity, NullWritable, NullWritable> {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(ReIndexMapper.class.getName());
private static class Handler {
@Inject CheckedDatastore datastore;
@Inject @ConvStore SlobFacilities facilities;
@Inject WaveIndex index;
void process(Context context, final Key key) throws PermanentFailure {
new RetryHelper().run(new RetryHelper.VoidBody() {
@Override public void run() throws PermanentFailure, RetryableFailure {
CheckedTransaction tx = datastore.beginTransaction();
try {
SlobId objectId = facilities.parseRootEntityKey(key);
MutationLog mutationLog = facilities.getMutationLogFactory().create(tx, objectId);
try {
ObsoleteWaveletMetadata metadata = GsonProto.fromGson(
new ObsoleteWaveletMetadataGsonImpl(), mutationLog.getMetadata());
if (metadata.getType() != ObsoleteWaveletMetadata.Type.CONV) {
throw new RuntimeException(objectId + ": Not CONV: " + metadata);
}
} catch (MessageException e) {
throw new RuntimeException("Failed to parse metadata for " + objectId, e);
}
StateAndVersion state = mutationLog.reconstruct(null);
log.info("Re-indexing " + objectId + " at version " + state.getVersion());
index.update(tx, objectId, (ReadableWaveletObject) state.getState());
tx.commit();
} finally {
tx.close();
}
}
});
}
}
@Override
public void map(Key key, Entity value, Context context) throws IOException {
context.getCounter(getClass().getSimpleName(), "entities-seen").increment(1);
log.info("Re-indexing " + key);
try {
GuiceSetup.getInjectorForTaskQueueTask().getInstance(Handler.class).process(context, key);
} catch (PermanentFailure e) {
throw new IOException("PermanentFailure re-indexing key " + key, e);
}
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.wave.server.wavemanager;
import static com.google.common.base.Preconditions.checkNotNull;
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.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
import com.google.walkaround.slob.server.SlobFacilities;
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;
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 com.google.walkaround.wave.server.conv.ConvStore;
import com.google.walkaround.wave.server.model.WaveObjectStoreModel.ReadableWaveletObject;
import org.waveprotocol.wave.model.util.ValueUtils;
import org.waveprotocol.wave.model.wave.ParticipantId;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Manages indexing and ACL storage.
*
* @author ohler@google.com (Christian Ohler)
*/
public class WaveIndex {
// We want one entity group per wave. We use the same entity group as the
// mutation log so that we can transactionally update a conv wavelet and the
// ACL, since we sync that from the participant list. The problem may look
// similar to indexing at first, but delays would be much more irritating, and
// the fan-out is smaller (no group expansion).
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(WaveIndex.class.getName());
static class IndexEntry {
private final SlobId objectId;
private final ParticipantId creator;
private final String title;
private final String snippet;
private final long lastModifiedMillis;
private final Set<ParticipantId> acl;
public IndexEntry(SlobId objectId,
ParticipantId creator,
String title,
String snippet,
long lastModifiedMillis,
Set<ParticipantId> acl) {
this.objectId = checkNotNull(objectId, "Null objectId");
this.creator = checkNotNull(creator, "Null creator");
this.title = checkNotNull(title, "Null title");
this.snippet = checkNotNull(snippet, "Null snippet");
this.lastModifiedMillis = lastModifiedMillis;
this.acl = checkNotNull(acl, "Null acl");
}
public SlobId getObjectId() {
return objectId;
}
public ParticipantId getCreator() {
return creator;
}
public String getTitle() {
return title;
}
public String getSnippet() {
return snippet;
}
public long getLastModifiedMillis() {
return lastModifiedMillis;
}
public Set<ParticipantId> getAcl() {
return acl;
}
@Override public String toString() {
return "IndexEntry("
+ objectId + ", "
+ creator + ", "
+ title + ", "
+ snippet + ", "
+ lastModifiedMillis + ", "
+ acl
+ ")";
}
@Override public final boolean equals(Object o) {
if (o == this) { return true; }
if (!(o instanceof IndexEntry)) { return false; }
IndexEntry other = (IndexEntry) o;
return lastModifiedMillis == other.lastModifiedMillis
&& Objects.equal(objectId, other.objectId)
&& Objects.equal(creator, other.creator)
&& Objects.equal(title, other.title)
&& Objects.equal(snippet, other.snippet)
&& Objects.equal(acl, other.acl);
}
@Override public final int hashCode() {
return Objects.hashCode(objectId, creator, title, snippet, lastModifiedMillis, acl);
}
}
private static final String INDEX_ENTITY_KIND = "ConvIndex";
private static final String INDEX_KEY = "index";
private static final String CREATOR_PROPERTY = "creator";
private static final String TITLE_PROPERTY = "title";
private static final String SNIPPET_PROPERTY = "snippet";
private static final String LAST_MODIFIED_MILLIS_PROPERTY = "lastModified";
private static final String ACL_PROPERTY = "p"; // for "participants"
public static final int MAX_TITLE_CHARS = 300;
public static final int MAX_SNIPPET_CHARS = 300;
private final CheckedDatastore datastore;
private final SlobFacilities facilities;
@Inject public WaveIndex(CheckedDatastore datastore,
@ConvStore SlobFacilities facilities) {
this.datastore = datastore;
this.facilities = facilities;
}
private Key makeKey(SlobId objectId) {
return KeyFactory.createKey(facilities.makeRootEntityKey(objectId),
INDEX_ENTITY_KIND, INDEX_KEY);
}
private Entity makeEntity(IndexEntry entry) {
// Can't truncate the strings in this function since that would mean
// parseEntity() is no longer its inverse.
Preconditions.checkArgument(entry.getTitle().length() <= MAX_TITLE_CHARS,
"Title too long: " + entry);
Preconditions.checkArgument(entry.getSnippet().length() <= MAX_SNIPPET_CHARS,
"Snippet too long: " + entry);
Entity entity = new Entity(makeKey(entry.getObjectId()));
ImmutableList.Builder<String> b = ImmutableList.builder();
for (ParticipantId user : entry.getAcl()) {
b.add(user.getAddress());
}
entity.setProperty(ACL_PROPERTY, b.build());
DatastoreUtil.setNonNullIndexedProperty(entity, CREATOR_PROPERTY,
entry.getCreator().getAddress());
DatastoreUtil.setNonNullIndexedProperty(entity, TITLE_PROPERTY, entry.getTitle());
DatastoreUtil.setNonNullIndexedProperty(entity, SNIPPET_PROPERTY, entry.getSnippet());
DatastoreUtil.setNonNullIndexedProperty(entity, LAST_MODIFIED_MILLIS_PROPERTY,
entry.getLastModifiedMillis());
Assert.check(entry.equals(parseEntity(entity)), "Mismatch serializing %s: %s", entry, entity);
return entity;
}
private IndexEntry parseEntity(Entity entity) {
SlobId objectId = new SlobId(entity.getKey().getParent().getName());
@SuppressWarnings("unchecked") // We only put in List<String>
Collection<String> rawIds = (Collection<String>) entity.getProperty(ACL_PROPERTY);
Set<ParticipantId> acl;
if (rawIds == null) {
acl = Collections.emptySet();
} else {
ImmutableSortedSet.Builder<ParticipantId> b = ImmutableSortedSet.naturalOrder();
for (String id : rawIds) {
b.add(ParticipantId.ofUnsafe(id));
}
acl = b.build();
}
return new IndexEntry(
objectId,
ParticipantId.ofUnsafe(
DatastoreUtil.getExistingProperty(entity, CREATOR_PROPERTY, String.class)),
DatastoreUtil.getExistingProperty(entity, TITLE_PROPERTY, String.class),
DatastoreUtil.getExistingProperty(entity, SNIPPET_PROPERTY, String.class),
DatastoreUtil.getExistingProperty(entity, LAST_MODIFIED_MILLIS_PROPERTY, Long.class),
acl);
}
// TODO(ohler): Take indexable text as an argument; writing indexable text
// should only be part of this function if indexing can be done
// transactionally, though.
private void update(CheckedTransaction tx, SlobId objectId, IndexEntry entry)
throws RetryableFailure, PermanentFailure {
log.info("Updating index for " + objectId + ": " + entry);
tx.put(makeEntity(entry));
// TODO(ohler): Make the ACL cache consistent with the datastore.
}
public void update(CheckedTransaction tx, SlobId objectId, ReadableWaveletObject convState)
throws RetryableFailure, PermanentFailure {
update(tx, objectId,
new IndexEntry(objectId, convState.getCreator(),
ValueUtils.abbrev(convState.getTitle(), MAX_TITLE_CHARS),
ValueUtils.abbrev(convState.getSnippet(), MAX_SNIPPET_CHARS),
convState.getLastModifiedMillis(),
Sets.newHashSet(convState.getParticipants())));
}
@Nullable public IndexEntry getEntry(CheckedTransaction tx, SlobId objectId)
throws RetryableFailure, PermanentFailure {
Entity entity = tx.get(makeKey(objectId));
IndexEntry result = entity == null ? null : parseEntity(entity);
log.info("Index entry for " + objectId + ": " + result);
return result;
}
// TODO(ohler): make this scalable, e.g. by adding pagination
public List<IndexEntry> getAllWaves(ParticipantId participantId)
throws RetryableFailure, PermanentFailure {
log.info("getAllWaves(" + participantId + ")");
CheckedIterator i = datastore.prepareNontransactionalQuery(new Query(INDEX_ENTITY_KIND)
.addFilter(ACL_PROPERTY, Query.FilterOperator.EQUAL, participantId.getAddress())
.addSort(LAST_MODIFIED_MILLIS_PROPERTY, Query.SortDirection.DESCENDING))
.asIterator();
ImmutableList.Builder<IndexEntry> b = ImmutableList.builder();
while (i.hasNext()) {
b.add(parseEntity(i.next()));
}
List<IndexEntry> out = b.build();
log.info("got " + out.size() + " waves");
return out;
}
}
| 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.server.wavemanager;
import com.google.common.collect.ImmutableList;
import com.google.common.net.UriEscapers;
import com.google.gxp.base.GxpContext;
import com.google.gxp.html.HtmlClosure;
import com.google.inject.Inject;
import com.google.walkaround.slob.shared.SlobId;
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.auth.InvalidSecurityTokenException;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import com.google.walkaround.util.server.servlet.BadRequestException;
import com.google.walkaround.wave.server.Flag;
import com.google.walkaround.wave.server.FlagName;
import com.google.walkaround.wave.server.WaveletCreator;
import com.google.walkaround.wave.server.auth.XsrfHelper;
import com.google.walkaround.wave.server.auth.XsrfHelper.XsrfTokenExpiredException;
import com.google.walkaround.wave.server.gxp.InboxDisplayRecord;
import com.google.walkaround.wave.server.gxp.InboxFragment;
import com.google.walkaround.wave.server.gxp.Welcome;
import com.google.walkaround.wave.server.servlet.PageSkinWriter;
import com.google.walkaround.wave.server.wavemanager.WaveIndex.IndexEntry;
import org.joda.time.Instant;
import org.joda.time.LocalDate;
import org.waveprotocol.wave.model.wave.ParticipantId;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Lists waves relevant to the user.
*
* @author ohler@google.com (Christian Ohler)
*/
public class InboxHandler extends AbstractHandler {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(InboxHandler.class.getName());
private static final String XSRF_ACTION = "inboxaction";
@Inject ParticipantId participantId;
@Inject XsrfHelper xsrfHelper;
@Inject CheckedDatastore datastore;
@Inject WaveIndex index;
@Inject WaveletCreator waveletCreator;
@Inject @Flag(FlagName.ANNOUNCEMENT_HTML) String announcementHtml;
@Inject PageSkinWriter pageSkinWriter;
private String queryEscape(String s) {
return UriEscapers.uriQueryStringEscaper(false).escape(s);
}
private String makeWaveLink(SlobId objectId) {
return "/wave?id=" + queryEscape(objectId.getId());
}
private List<InboxDisplayRecord> getWavesInner() throws RetryableFailure, PermanentFailure {
ImmutableList.Builder<InboxDisplayRecord> out = ImmutableList.builder();
List<IndexEntry> waves = index.getAllWaves(participantId);
for (IndexEntry wave : waves) {
out.add(new InboxDisplayRecord(
wave.getCreator().getAddress(),
wave.getTitle().trim(),
wave.getSnippet().trim(),
"" + new LocalDate(new Instant(wave.getLastModifiedMillis())),
makeWaveLink(wave.getObjectId())));
}
return out.build();
}
private List<InboxDisplayRecord> getWaves() throws IOException {
try {
return new RetryHelper().run(
new RetryHelper.Body<List<InboxDisplayRecord>>() {
@Override public List<InboxDisplayRecord> run()
throws RetryableFailure, PermanentFailure {
return getWavesInner();
}
});
} catch (PermanentFailure e) {
throw new IOException("PermanentFailure reading index", e);
}
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
List<InboxDisplayRecord> waveRecords = getWaves();
String token = xsrfHelper.createToken(XSRF_ACTION);
resp.setContentType("text/html");
resp.setCharacterEncoding("UTF-8");
pageSkinWriter.write("Walkaround", participantId.getAddress(),
waveRecords.isEmpty()
? Welcome.getGxpClosure(token)
: InboxFragment.getGxpClosure(token,
announcementHtml.isEmpty()
? null
: new HtmlClosure() {
@Override public void write(Appendable out, GxpContext context) throws IOException {
out.append(announcementHtml);
}
},
waveRecords));
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
try {
xsrfHelper.verify(XSRF_ACTION, requireParameter(req, "token"));
} catch (XsrfTokenExpiredException e) {
throw new BadRequestException(e);
} catch (InvalidSecurityTokenException e) {
throw new BadRequestException(e);
}
String action = requireParameter(req, "action");
if ("newwave".equals(action)) {
SlobId newWaveId = waveletCreator.newConvWithGeneratedId(null, null, false);
// TODO(ohler): Send 303, not 302. See
// http://en.wikipedia.org/wiki/Post/Redirect/Get .
resp.sendRedirect(makeWaveLink(newWaveId));
} else {
throw new BadRequestException("Unknown action: " + action);
}
}
}
| 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.server.wavemanager;
import com.google.inject.Inject;
import com.google.walkaround.proto.ConvMetadata;
import com.google.walkaround.slob.server.MutationLog;
import com.google.walkaround.slob.server.SlobFacilities;
import com.google.walkaround.slob.server.SlobManager;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.slob.shared.StateAndVersion;
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.wave.server.conv.ConvMetadataStore;
import com.google.walkaround.wave.server.conv.ConvStore;
import com.google.walkaround.wave.server.conv.PermissionCache;
import com.google.walkaround.wave.server.conv.PermissionCache.Permissions;
import com.google.walkaround.wave.server.model.WaveObjectStoreModel.ReadableWaveletObject;
import org.waveprotocol.wave.model.wave.ParticipantId;
import java.io.IOException;
import java.util.logging.Logger;
/**
* Extracts permissions from conv wavelets.
*
* @author ohler@google.com (Christian Ohler)
*/
// TODO(ohler): Rename to ConvPermissionSource and move to conv.
public class WaveManager implements SlobManager, PermissionCache.PermissionSource {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(WaveManager.class.getName());
private final ParticipantId participantId;
private final SlobFacilities convSlobFacilities;
private final CheckedDatastore datastore;
private final ConvMetadataStore convMetadataStore;
@Inject
public WaveManager(ParticipantId participantId,
@ConvStore SlobFacilities convSlobFacilities,
CheckedDatastore datastore,
ConvMetadataStore convMetadataStore) {
this.participantId = participantId;
this.convSlobFacilities = convSlobFacilities;
this.datastore = datastore;
this.convMetadataStore = convMetadataStore;
}
@Override
public Permissions getPermissions(final SlobId slobId) throws IOException {
try {
return new RetryHelper().run(
new RetryHelper.Body<Permissions>() {
@Override public Permissions run() throws RetryableFailure, PermanentFailure {
CheckedTransaction tx = datastore.beginTransaction();
try {
ConvMetadata metadata = convMetadataStore.get(tx, slobId);
if (metadata.hasImportMetadata()
&& !metadata.getImportMetadata().getImportFinished()) {
log.info(slobId + " still importing; " + participantId + " may not access");
return new Permissions(false, false);
}
// Can't use SlobStore here, that would be a cyclic dependency.
MutationLog mutationLog = convSlobFacilities.getMutationLogFactory()
.create(tx, slobId);
StateAndVersion stateAndVersion = mutationLog.reconstruct(null);
if (stateAndVersion.getVersion() == 0) {
log.info(slobId + " does not exist; " + participantId + " may not access");
return new Permissions(false, false);
}
// TODO(ohler): introduce generics to avoid the cast.
ReadableWaveletObject wavelet = (ReadableWaveletObject) stateAndVersion.getState();
if (wavelet.getParticipants().contains(participantId)) {
log.info(slobId + " exists and " + participantId + " is on the participant list");
return new Permissions(true, true);
} else {
log.info(slobId + " exists but "
+ participantId + " is not on the participant list");
return new Permissions(false, false);
}
} finally {
tx.close();
}
}
});
} catch (PermanentFailure e) {
throw new IOException("Failed to get permissions for " + slobId);
}
}
@Override
public void update(SlobId objectId, SlobIndexUpdate update) throws IOException {
// Nothing to do for now since we index in our pre-commit hook.
}
}
| 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.server.model;
import com.google.walkaround.util.shared.RandomBase64Generator;
import com.google.walkaround.wave.shared.IdHack;
import org.waveprotocol.wave.model.conversation.Conversation;
import org.waveprotocol.wave.model.conversation.ConversationThread;
import org.waveprotocol.wave.model.conversation.ConversationView;
import org.waveprotocol.wave.model.conversation.WaveBasedConversationView;
import org.waveprotocol.wave.model.id.IdGenerator;
import org.waveprotocol.wave.model.id.WaveId;
import org.waveprotocol.wave.model.id.WaveletId;
import org.waveprotocol.wave.model.operation.OperationException;
import org.waveprotocol.wave.model.operation.OperationRuntimeException;
import org.waveprotocol.wave.model.operation.SilentOperationSink;
import org.waveprotocol.wave.model.operation.wave.AddParticipant;
import org.waveprotocol.wave.model.operation.wave.BasicWaveletOperationContextFactory;
import org.waveprotocol.wave.model.operation.wave.WaveletOperation;
import org.waveprotocol.wave.model.operation.wave.WaveletOperationContext;
import org.waveprotocol.wave.model.testing.BasicFactories;
import org.waveprotocol.wave.model.testing.FakeDocument;
import org.waveprotocol.wave.model.version.HashedVersion;
import org.waveprotocol.wave.model.wave.ParticipantId;
import org.waveprotocol.wave.model.wave.ParticipationHelper;
import org.waveprotocol.wave.model.wave.data.ObservableWaveletData;
import org.waveprotocol.wave.model.wave.data.ReadableWaveletData;
import org.waveprotocol.wave.model.wave.data.impl.WaveViewDataImpl;
import org.waveprotocol.wave.model.wave.data.impl.WaveletDataImpl;
import org.waveprotocol.wave.model.wave.opbased.OpBasedWavelet;
import org.waveprotocol.wave.model.wave.opbased.WaveViewImpl;
import org.waveprotocol.wave.model.wave.opbased.WaveViewImpl.WaveletConfigurator;
import org.waveprotocol.wave.model.wave.opbased.WaveViewImpl.WaveletFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
/**
* Utilities for initial operations on wavelets.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class InitialOps {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(InitialOps.class.getName());
public static List<WaveletOperation> conversationWaveletOps(final ParticipantId creator,
final long creationTime, final RandomBase64Generator random) {
final List<WaveletOperation> ops = new ArrayList<WaveletOperation>();
final SilentOperationSink<WaveletOperation> sink = new SilentOperationSink<WaveletOperation>() {
@Override public void consume(WaveletOperation op) {
ops.add(op);
}
};
IdGenerator gen = new IdHack.MinimalIdGenerator(
// Fake wavelet ID since we always use fake wavelet IDs on the server
// side (they are never persisted). The UDW ID is not needed in the
// code below but the model code asks for it anyway. We arbitrarily use
// DISABLED_UDW_ID.
IdHack.FAKE_WAVELET_NAME.waveletId, IdHack.DISABLED_UDW_ID,
random);
final WaveViewDataImpl waveData = WaveViewDataImpl.create(IdHack.FAKE_WAVELET_NAME.waveId);
final FakeDocument.Factory docFactory = BasicFactories.fakeDocumentFactory();
final ObservableWaveletData.Factory<?> waveletDataFactory =
new ObservableWaveletData.Factory<WaveletDataImpl>() {
private final ObservableWaveletData.Factory<WaveletDataImpl> inner =
WaveletDataImpl.Factory.create(docFactory);
@Override
public WaveletDataImpl create(ReadableWaveletData data) {
WaveletDataImpl wavelet = inner.create(data);
waveData.addWavelet(wavelet);
return wavelet;
}
};
WaveletFactory<OpBasedWavelet> waveletFactory = new WaveletFactory<OpBasedWavelet>() {
@Override
public OpBasedWavelet create(WaveId waveId, WaveletId waveletId, ParticipantId creator) {
final WaveletDataImpl data = new WaveletDataImpl(
waveletId,
creator,
creationTime,
0L,
HashedVersion.unsigned(0),
creationTime,
waveId,
docFactory);
SilentOperationSink<WaveletOperation> executor =
new SilentOperationSink<WaveletOperation>() {
@Override
public void consume(WaveletOperation operation) {
try {
operation.apply(data);
} catch (OperationException e) {
throw new OperationRuntimeException("Error applying op", e);
}
}
};
return new OpBasedWavelet(waveId,
data,
new BasicWaveletOperationContextFactory(creator) {
@Override public long currentTimeMillis() {
return creationTime;
}
},
ParticipationHelper.IGNORANT,
executor,
sink);
}
};
WaveViewImpl<?> wave = WaveViewImpl.create(
waveletFactory, waveData.getWaveId(), gen, creator, WaveletConfigurator.ADD_CREATOR);
// Build a conversation with a root blip.
ConversationView v = WaveBasedConversationView.create(wave, gen);
Conversation c = v.createRoot();
ConversationThread thread = c.getRootThread();
thread.appendBlip();
log.info("initial ops=" + ops);
return ops;
}
public static List<WaveletOperation> userDataWaveletOps(ParticipantId user, long creationTime) {
return Collections.<WaveletOperation>singletonList(
new AddParticipant(new WaveletOperationContext(user, creationTime, 0L), user));
}
}
| 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.server.model;
import com.google.common.base.Preconditions;
import com.google.walkaround.proto.Delta;
import com.google.walkaround.proto.OperationBatch;
import com.google.walkaround.proto.ProtocolWaveletOperation;
import com.google.walkaround.proto.WalkaroundWaveletSnapshot;
import com.google.walkaround.proto.WaveletDiffSnapshot;
import com.google.walkaround.proto.gson.DeltaGsonImpl;
import com.google.walkaround.proto.gson.OperationBatchGsonImpl;
import com.google.walkaround.proto.gson.ProtocolWaveletOperationGsonImpl;
import com.google.walkaround.proto.gson.WalkaroundWaveletSnapshotGsonImpl;
import com.google.walkaround.proto.gson.WaveletDiffSnapshotGsonImpl;
import com.google.walkaround.slob.server.GsonProto;
import com.google.walkaround.slob.shared.MessageException;
import com.google.walkaround.wave.shared.MessageFactoryHelper;
import com.google.walkaround.wave.shared.MessageSerializer;
import org.waveprotocol.wave.communication.gson.GsonSerializable;
/**
* Server-side version of serializer. It (de)serializes wavelets and deltas to
* and from JSON in server environment.
*
* @author piotrkaleta@google.com (Piotr Kaleta)
*/
public class ServerMessageSerializer implements MessageSerializer {
/**
* Constructs new server-side serializer
*/
public ServerMessageSerializer() {
if (MessageFactoryHelper.getFactory() == null) {
MessageFactoryHelper.setFactory(new MessageFactoryServer());
} else {
Preconditions.checkState(MessageFactoryHelper.getFactory() instanceof MessageFactoryServer);
}
}
@Override
public String serializeWavelet(WalkaroundWaveletSnapshot waveletSnapshot) {
return GsonProto.toJson((GsonSerializable) waveletSnapshot);
}
@Override
public WalkaroundWaveletSnapshot deserializeWavelet(String serializedSnapshot)
throws MessageException {
return GsonProto.fromGson(new WalkaroundWaveletSnapshotGsonImpl(), serializedSnapshot);
}
@Override
public String serializeOp(ProtocolWaveletOperation waveletOp) {
return GsonProto.toJson((GsonSerializable) waveletOp);
}
@Override
public ProtocolWaveletOperation deserializeOp(String serializedOp) throws MessageException {
return GsonProto.fromGson(new ProtocolWaveletOperationGsonImpl(), serializedOp);
}
@Override
public String serializeDiff(WaveletDiffSnapshot diff) {
return GsonProto.toJson((GsonSerializable) diff);
}
@Override
public WaveletDiffSnapshot deserializeDiff(String serializedDiff) throws MessageException {
return GsonProto.fromGson(new WaveletDiffSnapshotGsonImpl(), serializedDiff);
}
@Override
public String serializeOperationBatch(OperationBatch batch) {
return GsonProto.toJson((OperationBatchGsonImpl) batch);
}
@Override
public OperationBatch deserializeOperationBatch(String serialized) throws MessageException {
return GsonProto.fromGson(new OperationBatchGsonImpl(), serialized);
}
@Override
public String serializeDelta(Delta input) {
return GsonProto.toJson((DeltaGsonImpl) input);
}
@Override
public Delta deserializeDelta(String input) throws MessageException {
return GsonProto.fromGson(new DeltaGsonImpl(), input);
}
}
| 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.server.model;
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.gson.DeltaGsonImpl;
import com.google.walkaround.proto.gson.DocumentDiffSnapshotGsonImpl;
import com.google.walkaround.proto.gson.OperationBatchGsonImpl;
import com.google.walkaround.proto.gson.ProtocolDocumentOperationGsonImpl;
import com.google.walkaround.proto.gson.ProtocolDocumentOperationGsonImpl.ComponentGsonImpl;
import com.google.walkaround.proto.gson.ProtocolDocumentOperationGsonImpl.ComponentGsonImpl.AnnotationBoundaryGsonImpl;
import com.google.walkaround.proto.gson.ProtocolDocumentOperationGsonImpl.ComponentGsonImpl.ElementStartGsonImpl;
import com.google.walkaround.proto.gson.ProtocolDocumentOperationGsonImpl.ComponentGsonImpl.KeyValuePairGsonImpl;
import com.google.walkaround.proto.gson.ProtocolDocumentOperationGsonImpl.ComponentGsonImpl.KeyValueUpdateGsonImpl;
import com.google.walkaround.proto.gson.ProtocolDocumentOperationGsonImpl.ComponentGsonImpl.ReplaceAttributesGsonImpl;
import com.google.walkaround.proto.gson.ProtocolDocumentOperationGsonImpl.ComponentGsonImpl.UpdateAttributesGsonImpl;
import com.google.walkaround.proto.gson.ProtocolWaveletOperationGsonImpl;
import com.google.walkaround.proto.gson.ProtocolWaveletOperationGsonImpl.MutateDocumentGsonImpl;
import com.google.walkaround.proto.gson.WalkaroundDocumentSnapshotGsonImpl;
import com.google.walkaround.proto.gson.WalkaroundWaveletSnapshotGsonImpl;
import com.google.walkaround.proto.gson.WaveletDiffSnapshotGsonImpl;
import com.google.walkaround.wave.shared.MessageFactory;
public class MessageFactoryServer implements MessageFactory {
@Override
public OperationBatch createOperationBatch() {
return new OperationBatchGsonImpl();
}
@Override
public ProtocolWaveletOperation createWaveOp() {
return new ProtocolWaveletOperationGsonImpl();
}
@Override
public ElementStart createDocumentElementStart() {
return new ElementStartGsonImpl();
}
@Override
public ReplaceAttributes createDocumentReplaceAttributes() {
return new ReplaceAttributesGsonImpl();
}
@Override
public UpdateAttributes createDocumentUpdateAttributes() {
return new UpdateAttributesGsonImpl();
}
@Override
public AnnotationBoundary createDocumentAnnotationBoundary() {
return new AnnotationBoundaryGsonImpl();
}
@Override
public Component createDocumentOperationComponent() {
return new ComponentGsonImpl();
}
@Override
public ProtocolDocumentOperation createDocumentOperation() {
return new ProtocolDocumentOperationGsonImpl();
}
@Override
public MutateDocument createMutateDocument() {
return new MutateDocumentGsonImpl();
}
@Override
public KeyValuePair createDocumentKeyValuePair() {
return new KeyValuePairGsonImpl();
}
@Override
public KeyValueUpdate createDocumentKeyValueUpdate() {
return new KeyValueUpdateGsonImpl();
}
@Override
public WalkaroundDocumentSnapshot createDocumentSnapshot() {
return new WalkaroundDocumentSnapshotGsonImpl();
}
@Override
public WalkaroundWaveletSnapshot createWaveletSnapshot() {
return new WalkaroundWaveletSnapshotGsonImpl();
}
@Override
public DocumentDiffSnapshot createDocumentDiffSnapshot() {
return new DocumentDiffSnapshotGsonImpl();
}
@Override
public WaveletDiffSnapshot createWaveletDiffSnapshot() {
return new WaveletDiffSnapshotGsonImpl();
}
@Override
public Delta createDelta() {
return new DeltaGsonImpl();
}
}
| 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.server.model;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Text;
import com.google.inject.Inject;
import com.google.walkaround.proto.gson.DeltaGsonImpl;
import com.google.walkaround.slob.server.GsonProto;
import com.google.walkaround.slob.server.MutationLog.DefaultDeltaEntityConverter;
import com.google.walkaround.slob.server.MutationLog.DeltaEntityConverter;
import com.google.walkaround.slob.shared.ChangeData;
import com.google.walkaround.slob.shared.ClientId;
import com.google.walkaround.slob.shared.MessageException;
import com.google.walkaround.util.server.appengine.DatastoreUtil;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Converts entities in a legacy format that have a single property {@code Data}
* whose value is a JSON map with the keys {@code sid}, {@code author},
* {@code time}, and {@code op}. The value in the {@code author} field is
* additionally wrapped in another JSON map with a single key {@code email}.
*
* Example:
* <code>{"sid":"abc","author":{"email":"foo@example.com"},"time":1312167950103,"op":{...}}</code>
*
* @author ohler@google.com (Christian Ohler)
*/
public class LegacyDeltaEntityConverter implements DeltaEntityConverter {
private static final String DATA_PROPERTY = "Data";
private static final ServerMessageSerializer SERIALIZER = new ServerMessageSerializer();
private final DefaultDeltaEntityConverter next;
@Inject LegacyDeltaEntityConverter(DefaultDeltaEntityConverter next) {
this.next = next;
}
@Override public ChangeData<String> convert(Entity entity) {
if (!entity.hasProperty(DATA_PROPERTY)) {
return next.convert(entity);
} else {
String json = DatastoreUtil.getExistingProperty(entity, DATA_PROPERTY, Text.class).getValue();
try {
JSONObject obj = new JSONObject(json);
DeltaGsonImpl delta = new DeltaGsonImpl();
delta.setAuthor(obj.getJSONObject("author").getString("email"));
delta.setTimestampMillis(obj.getLong("time"));
delta.setOperation(SERIALIZER.deserializeOp(obj.getJSONObject("op").toString()));
return new ChangeData<String>(new ClientId(obj.getString("sid")),
GsonProto.toJson(delta));
} catch (MessageException e) {
throw new RuntimeException("MessageException converting " + entity, e);
} catch (JSONException e) {
throw new RuntimeException("JSONException converting " + entity, 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.wave.server.model;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import com.google.walkaround.slob.shared.ChangeData;
import com.google.walkaround.slob.shared.ChangeRejected;
import com.google.walkaround.slob.shared.InvalidSnapshot;
import com.google.walkaround.slob.shared.MessageException;
import com.google.walkaround.slob.shared.SlobModel;
import com.google.walkaround.wave.shared.IdHack;
import com.google.walkaround.wave.shared.MessageSerializer;
import com.google.walkaround.wave.shared.WaveSerializer;
import com.google.walkaround.wave.shared.WaveletUtil;
import org.waveprotocol.wave.model.operation.OperationException;
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.wave.ParticipantId;
import org.waveprotocol.wave.model.wave.data.impl.WaveletDataImpl;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
/**
* @author danilatos@google.com (Daniel Danilatos)
*/
public class WaveObjectStoreModel implements SlobModel {
// TODO(ohler): Replace these methods with getIndexEntry().
public interface ReadableWaveletObject extends SlobModel.ReadableSlob {
ParticipantId getCreator();
// TODO(ohler): Define separate models for conv wavelets and UDWs; this
// stuff makes no sense on UDWs.
String getTitle();
String getSnippet();
long getLastModifiedMillis();
List<ParticipantId> getParticipants();
}
private class WaveletObject implements ReadableWaveletObject, SlobModel.Slob {
/**
* Wavelet state. Created from first delta, then mutated in {@link #apply}.
* Never cleared.
*/
private WaveletDataImpl wavelet;
private String cachedSnapshot = null;
public WaveletObject(WaveletDataImpl initialState) {
this.wavelet = initialState;
}
@Override @Nullable
public String snapshot() {
if (wavelet == null) {
return null;
}
if (cachedSnapshot == null) {
cachedSnapshot = serializer.serializeWavelet(wavelet);
}
return cachedSnapshot;
}
@Override
public void apply(ChangeData<String> change) throws ChangeRejected {
cachedSnapshot = null;
WaveletOperation op;
try {
op = serializer.deserializeDelta(change.getPayload());
} catch (MessageException e) {
throw new ChangeRejected("Malformed op: " + change, e);
}
if (wavelet == null) {
try {
wavelet = WaveletUtil.buildWaveletFromInitialOps(
IdHack.FAKE_WAVELET_NAME, Collections.singletonList(op));
} catch (OperationException e) {
throw new ChangeRejected("Invalid initial op: " + op, e);
}
} else {
try {
op.apply(wavelet);
} catch (OperationException e) {
// Operation failed. The wavelet is still intact, however, so just
// report the failure and continue on.
throw new ChangeRejected("Invalid op at version " + wavelet.getVersion() + ": " + op, e);
}
}
}
@Override public String getIndexedHtml() {
return wavelet == null ? "" : TextRenderer.renderToHtml(wavelet);
}
// TODO(ohler): Guarantee that the only method that will ever be called at
// version 0 is apply().
@Override public ParticipantId getCreator() {
return wavelet.getCreator();
}
@Override public String getTitle() {
// TODO(ohler): extract title
return "";
}
// Getting a snippet as a function of just the current state of the wave is
// not what we really want; we should be extracting a snippet from the wave
// based on the search query, or based on which blips the user hasn't read
// yet. TODO(ohler): redo this when we integrate with full text search.
@Override public String getSnippet() {
return TextRenderer.renderToText(wavelet);
}
@Override public long getLastModifiedMillis() {
return wavelet.getLastModifiedTime();
}
@Override public List<ParticipantId> getParticipants() {
return ImmutableList.copyOf(wavelet.getParticipants());
}
}
private final WaveSerializer serializer;
@Inject
public WaveObjectStoreModel(MessageSerializer messageSerializer) {
this.serializer = new WaveSerializer(messageSerializer);
}
@Override
public Slob create(String snapshot) throws InvalidSnapshot {
try {
return new WaveletObject(snapshot == null ? null
: serializer.deserializeWavelet(IdHack.FAKE_WAVELET_NAME, snapshot));
} catch (MessageException e) {
throw new InvalidSnapshot(e);
}
}
@Override
public List<String> transform(
List<ChangeData<String>> clientChanges, List<ChangeData<String>> serverChanges)
throws ChangeRejected {
try {
WaveletOperation[] clientOps = deserializeOps(clientChanges);
WaveletOperation[] serverOps = serverOps(serverChanges);
for (WaveletOperation serverOp : serverOps) {
for (int i = 0; i < clientOps.length; i++) {
OperationPair<WaveletOperation> pair = Transform.transform(clientOps[i], serverOp);
serverOp = pair.serverOp();
clientOps[i] = pair.clientOp();
}
}
List<String> ret = Lists.newArrayListWithCapacity(clientOps.length);
for (int i = 0; i < clientOps.length; i++) {
ret.add(serializer.serializeDelta(clientOps[i]));
}
return ret;
} catch (TransformException e) {
throw new ChangeRejected(e);
} catch (MessageException e) {
throw new ChangeRejected(e);
}
}
// Server ops aren't expected to fail deserialization.
private WaveletOperation[] serverOps(List<ChangeData<String>> serverChanges) {
try {
return deserializeOps(serverChanges);
} catch (MessageException e) {
throw new IllegalArgumentException("Malformed server op(s) " + serverChanges, e);
}
}
private WaveletOperation[] deserializeOps(List<ChangeData<String>> changes)
throws MessageException {
WaveletOperation[] ops = new WaveletOperation[changes.size()];
for (int i = 0; i < changes.size(); i++) {
ChangeData<String> delta = changes.get(i);
ops[i] = serializer.deserializeDelta(delta.getPayload());
}
return ops;
}
}
| 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.server.model;
import com.google.walkaround.util.server.HtmlEscaper;
import org.waveprotocol.wave.model.document.operation.AnnotationBoundaryMap;
import org.waveprotocol.wave.model.document.operation.Attributes;
import org.waveprotocol.wave.model.document.operation.DocInitialization;
import org.waveprotocol.wave.model.document.operation.DocInitializationCursor;
import org.waveprotocol.wave.model.wave.data.ReadableWaveletData;
/**
* Renders a wave as HTML text, for indexing. The rendering is just the text of
* each document, arbitrarily ordered.
*
* @author hearnden@google.com (David Hearnden)
*/
public final class TextRenderer {
private TextRenderer() {}
/**
* Renders a wavelet into simple HTML.
*/
public static String renderToHtml(ReadableWaveletData data) {
return HtmlEscaper.HTML_ESCAPER.escape(renderToText(data));
}
/** Renders a wavelet into text. */
public static String renderToText(ReadableWaveletData data) {
StringBuilder b = new StringBuilder();
for (String id : data.getDocumentIds()) {
// TODO(ohler): Find out whether this should be restricted to blip ids.
render(data.getDocument(id).getContent().asOperation(), b);
}
return b.toString();
}
/**
* Renders a document as a paragraph of plain text.
*/
private static void render(DocInitialization doc, final StringBuilder out) {
doc.apply(new DocInitializationCursor() {
@Override
public void characters(String chars) {
out.append(chars);
}
@Override
public void elementStart(String type, Attributes attrs) {
out.append(' ');
}
@Override
public void elementEnd() {
out.append(' ');
}
@Override
public void annotationBoundary(AnnotationBoundaryMap map) {
// Ignore
}
});
out.append("\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.wave.server;
import com.google.common.base.Preconditions;
import com.google.walkaround.slob.shared.SlobId;
import java.io.Serializable;
/**
* An entry in WaveletDirectory. This is just an SlobId. TODO(ohler): simplify
* this away.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class WaveletMapping implements Serializable {
private static final long serialVersionUID = 328650053195007979L;
private final SlobId objectId;
public WaveletMapping(SlobId objectId) {
Preconditions.checkNotNull(objectId, "Null objectId");
this.objectId = objectId;
}
public SlobId getObjectId() {
return objectId;
}
@Override
public String toString() {
return "WaveletMapping(" + objectId + ")";
}
}
| 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.server.udw;
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 SlobStore for user data wavelets.
*
* @author ohler@google.com (Christian Ohler)
*/
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface UdwStore {
}
| 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.server.udw;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.inject.PrivateModule;
import com.google.walkaround.slob.server.AccessChecker;
import com.google.walkaround.slob.server.PostCommitActionQueue;
import com.google.walkaround.slob.server.PostMutateHook;
import com.google.walkaround.slob.server.StoreModuleHelper;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.slob.shared.SlobModel;
import com.google.walkaround.wave.server.model.WaveObjectStoreModel;
import java.util.logging.Logger;
/**
* Guice module that configures an object store for user data wavelets.
*
* @author ohler@google.com (Christian Ohler)
*/
public class UdwStoreModule extends PrivateModule {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(UdwStoreModule.class.getName());
public static String ROOT_ENTITY_KIND = "Udw";
@Override protected void configure() {
StoreModuleHelper.makeBasicBindingsAndExposures(binder(), UdwStore.class);
StoreModuleHelper.bindEntityKinds(binder(), ROOT_ENTITY_KIND);
bind(SlobModel.class).to(WaveObjectStoreModel.class);
bind(AccessChecker.class).toInstance(
new AccessChecker() {
// We don't do access checks for UDWs here; we rely on WaveLoader to
// look up the correct UDW, and on our session security to make it
// impossible to access a UDW other than the one that WaveLoader
// returned.
@Override public void checkCanRead(SlobId objectId) {}
@Override public void checkCanModify(SlobId objectId) {}
@Override public void checkCanCreate(SlobId objectId) {}
});
bind(PostMutateHook.class).toInstance(PostMutateHook.NO_OP);
bind(Queue.class).annotatedWith(PostCommitActionQueue.class).toInstance(
QueueFactory.getQueue("post-commit-udw"));
}
}
| 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.server.udw;
import com.google.appengine.api.datastore.Entity;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.util.server.appengine.AbstractDirectory;
import com.google.walkaround.util.server.appengine.CheckedDatastore;
import com.google.walkaround.util.server.appengine.DatastoreUtil;
import com.google.walkaround.util.server.appengine.DatastoreUtil.InvalidPropertyException;
import com.google.walkaround.wave.server.auth.StableUserId;
import java.io.IOException;
import javax.annotation.Nullable;
/**
* @author danilatos@google.com (Daniel Danilatos)
* @author ohler@google.com (Christian Ohler)
*/
public class UserDataWaveletDirectory {
private static class Key {
private final SlobId convObjectId;
private final StableUserId userId;
public Key(SlobId convObjectId, StableUserId userId) {
Preconditions.checkNotNull(convObjectId, "Null convObjectId");
Preconditions.checkNotNull(userId, "Null userId");
Preconditions.checkArgument(!convObjectId.getId().contains(" "),
"Invalid convObjectId: %s", convObjectId);
Preconditions.checkArgument(!userId.getId().contains(" "),
"Invalid userId: %s", userId);
this.convObjectId = convObjectId;
this.userId = userId;
}
public SlobId getConvObjectId() {
return convObjectId;
}
public StableUserId getUserId() {
return userId;
}
@Override public String toString() {
return "Key(" + convObjectId + ", " + userId + ")";
}
@Override public boolean equals(Object o) {
if (o == this) { return true; }
if (o == null) { return false; }
if (!(o.getClass() == Key.class)) { return false; }
Key other = (Key) o;
return convObjectId.equals(other.convObjectId)
&& userId.equals(other.userId);
}
@Override public int hashCode() {
return Objects.hashCode(Key.class, convObjectId, userId);
}
}
private static class Entry {
private final Key key;
private final SlobId udwId;
public Entry(Key key, SlobId udwId) {
Preconditions.checkNotNull(key, "Null key");
Preconditions.checkNotNull(udwId, "Null udwId");
this.key = key;
this.udwId = udwId;
}
public Key getKey() {
return key;
}
public SlobId getUdwId() {
return udwId;
}
@Override public String toString() {
return "Entry(" + key + ", " + udwId + ")";
}
@Override public boolean equals(Object o) {
if (o == this) { return true; }
if (o == null) { return false; }
if (!(o.getClass() == Entry.class)) { return false; }
Entry other = (Entry) o;
return key.equals(other.key)
&& udwId.equals(other.udwId);
}
@Override public int hashCode() {
return Objects.hashCode(Entry.class, key, udwId);
}
}
@VisibleForTesting
static class Directory extends AbstractDirectory<Entry, Key> {
private static final String UDW_ID_PROPERTY = "UdwId";
Directory(CheckedDatastore datastore) {
// Increased to 3 because the metadata format has changed.
super(datastore, "UdwDirectoryEntry3");
}
@Override
protected String serializeId(Key key) {
return key.getConvObjectId().getId() + " " + key.getUserId().getId();
}
@Override
protected Key getId(Entry entry) {
return entry.getKey();
}
@Override
protected void populateEntity(Entry entry, Entity out) {
DatastoreUtil.setNonNullIndexedProperty(out, UDW_ID_PROPERTY, entry.getUdwId().getId());
}
private SlobId parseObjectId(Entity e, String propertyName, String objectIdStr) {
return new SlobId(objectIdStr);
}
@Override
protected Entry parse(Entity e) throws InvalidPropertyException {
String key = e.getKey().getName();
int space = key.indexOf(' ');
if (space == -1 || space != key.lastIndexOf(' ')) {
throw new InvalidPropertyException(e, "key");
}
SlobId convObjectId = parseObjectId(e, "key", key.substring(0, space));
StableUserId userId = new StableUserId(key.substring(space + 1));
SlobId udwId = parseObjectId(e, UDW_ID_PROPERTY,
DatastoreUtil.getExistingProperty(e, UDW_ID_PROPERTY, String.class));
return new Entry(new Key(convObjectId, userId), udwId);
}
}
private final Directory directory;
@Inject
public UserDataWaveletDirectory(CheckedDatastore datastore) {
this.directory = new Directory(datastore);
}
@Nullable public SlobId getUdwId(SlobId convObjectId, StableUserId userId) throws IOException {
Preconditions.checkNotNull(convObjectId, "Null convObjectId");
Preconditions.checkNotNull(userId, "Null userId");
Entry e = directory.getWithoutTx(new Key(convObjectId, userId));
return e == null ? null : e.getUdwId();
}
public SlobId getOrAdd(SlobId convObjectId, StableUserId userId, SlobId udwId)
throws IOException {
Preconditions.checkNotNull(convObjectId, "Null convObjectId");
Preconditions.checkNotNull(userId, "Null userId");
Preconditions.checkNotNull(udwId, "Null udwId");
Entry newEntry = new Entry(new Key(convObjectId, userId), udwId);
Entry existingEntry = directory.getOrAdd(newEntry);
if (existingEntry == null) {
return null;
} else {
return existingEntry.getUdwId();
}
}
}
| 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.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;
/**
* Annotates a <code>Map<FlagDeclaration, Object></code> that is used
* to retrieve flag values.
*
* The provided map must map each declaration to a non-null object of the type
* specified by <code>declaration.getType()</code>.
*
* @author ohler@google.com (Christian Ohler)
*/
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface FlagConfiguration {}
| 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.server;
import com.google.common.base.Preconditions;
import com.google.walkaround.util.server.flags.FlagDeclaration;
import java.lang.annotation.Annotation;
/**
* Walkaround flags.
*
* @author danilatos@google.com (Daniel Danilatos)
* @author ohler@google.com (Christian Ohler)
*/
public enum FlagName implements FlagDeclaration {
OAUTH_CLIENT_ID(String.class),
OAUTH_CLIENT_SECRET(String.class),
ENABLE_UDW(Boolean.class),
ENABLE_DIFF_ON_OPEN(Boolean.class),
ATTACHMENT_HEADER_BYTES_UPPER_BOUND(Integer.class),
MAX_THUMBNAIL_SAVED_SIZE_BYTES(Integer.class),
OBJECT_CHANNEL_EXPIRATION_SECONDS(Integer.class),
ACCESS_CACHE_EXPIRATION_SECONDS(Integer.class),
CLIENT_VERSION(Integer.class),
XSRF_TOKEN_EXPIRY_SECONDS(Integer.class),
STORE_SERVER(String.class),
NUM_STORE_SERVERS(Integer.class),
ANNOUNCEMENT_HTML(String.class),
ANALYTICS_ACCOUNT(String.class),
POST_COMMIT_ACTION_INTERVAL_MILLIS(Integer.class),
SLOB_LOCAL_CACHE_EXPIRATION_MILLIS(Integer.class),
IMPORT_PRESERVE_HISTORY(Boolean.class),
;
// Stolen from com.google.inject.name.NamedImpl.
static class FlagImpl implements Flag {
private final FlagName value;
FlagImpl(FlagName value) {
Preconditions.checkNotNull(value, "Null value");
this.value = value;
}
@Override public FlagName value() {
return value;
}
@Override public int hashCode() {
// This is specified in java.lang.Annotation.
return 127 * "value".hashCode() ^ value.hashCode();
}
@Override public boolean equals(Object o) {
if (!(o instanceof Flag)) {
return false;
}
Flag other = (Flag) o;
return value.equals(other.value());
}
@Override public String toString() {
return "@Flag(" + value + ")";
}
@Override public Class<? extends Annotation> annotationType() {
return Flag.class;
}
}
private final String name;
private final Class<?> type;
private FlagName(Class<?> type) {
this.name = name().toLowerCase();
this.type = type;
}
@Override public Annotation getAnnotation() {
return new FlagImpl(this);
}
@Override public String getName() {
return name;
}
@Override public Class<?> getType() {
return type;
}
}
| 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.server;
import com.google.appengine.api.backends.BackendService;
import com.google.appengine.api.backends.BackendServiceFactory;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;
import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.api.utils.SystemProperty;
import com.google.common.base.Joiner;
import com.google.inject.AbstractModule;
import com.google.inject.Key;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.google.inject.TypeLiteral;
import com.google.inject.name.Named;
import com.google.walkaround.slob.server.AffinityMutationProcessor.StoreBackendInstanceCount;
import com.google.walkaround.slob.server.AffinityMutationProcessor.StoreBackendName;
import com.google.walkaround.slob.server.MutationLog;
import com.google.walkaround.slob.server.PostCommitActionIntervalMillis;
import com.google.walkaround.slob.server.PostCommitTaskUrl;
import com.google.walkaround.slob.server.SlobLocalCacheExpirationMillis;
import com.google.walkaround.slob.server.SlobManager;
import com.google.walkaround.slob.server.SlobMessageRouter.SlobChannelExpirationSeconds;
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.Util;
import com.google.walkaround.util.server.appengine.CheckedDatastore;
import com.google.walkaround.util.server.appengine.CheckedDatastore.CheckedTransaction;
import com.google.walkaround.util.server.appengine.DatastoreUtil;
import com.google.walkaround.util.server.appengine.MemcacheDeletionQueue;
import com.google.walkaround.util.server.appengine.MemcacheTable;
import com.google.walkaround.util.server.auth.DigestUtils2.Secret;
import com.google.walkaround.util.server.flags.FlagDeclaration;
import com.google.walkaround.util.server.flags.FlagFormatException;
import com.google.walkaround.util.server.flags.JsonFlags;
import com.google.walkaround.util.server.gwt.StackTraceDeobfuscator.SymbolMapsDirectory;
import com.google.walkaround.util.server.gwt.ZipSymbolMapsDirectory;
import com.google.walkaround.util.shared.RandomBase64Generator.RandomProvider;
import com.google.walkaround.util.shared.RandomProviderAdapter;
import com.google.walkaround.wave.server.auth.OAuthInterstitialHandler.Scopes;
import com.google.walkaround.wave.server.conv.PermissionCache.PermissionCacheExpirationSeconds;
import com.google.walkaround.wave.server.googleimport.ImportTaskQueue;
import com.google.walkaround.wave.server.model.LegacyDeltaEntityConverter;
import com.google.walkaround.wave.server.model.ServerMessageSerializer;
import com.google.walkaround.wave.server.wavemanager.WaveManager;
import com.google.walkaround.wave.shared.MessageSerializer;
import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Map;
import java.util.Random;
import java.util.jar.JarFile;
import java.util.logging.Logger;
/**
* @author ohler@google.com (Christian Ohler)
*/
public class WalkaroundServerModule extends AbstractModule {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(WalkaroundServerModule.class.getName());
private static final String CONTACTS_SCOPE = "https://www.google.com/m8/feeds/";
private static final String WAVE_SCOPE = "http://wave.googleusercontent.com/api/rpc";
private static final String SECRET_ENTITY_KIND = "Secret";
private static final com.google.appengine.api.datastore.Key SECRET_KEY =
KeyFactory.createKey(SECRET_ENTITY_KIND, "secret");
private static final String SECRET_PROPERTY = "secret";
private <T> void bindToFlag(Class<T> type, Class<? extends Annotation> annotation,
FlagName flagName) {
bind(Key.get(type, annotation))
.toProvider(getProvider(Key.get(type, new FlagName.FlagImpl(flagName))));
}
@Override
protected void configure() {
// How heavyweight is SecureRandom? Until we know, let's use only one.
//
// This seems preferable over the .toInstance() below, but it doesn't work.
//bind(SecureRandom.class).in(Singleton.class);
final SecureRandom random = new SecureRandom();
bind(SecureRandom.class).toInstance(random);
bind(Random.class).to(SecureRandom.class);
bind(RandomProvider.class).to(RandomProviderAdapter.class);
bind(MemcacheTable.Factory.class).to(MemcacheTable.FactoryImpl.class);
bind(SystemProperty.Environment.Value.class).toInstance(SystemProperty.environment.value());
bind(Key.get(String.class, Scopes.class)).toInstance(
Joiner.on(" ").join(CONTACTS_SCOPE, WAVE_SCOPE));
bind(Key.get(Queue.class, ImportTaskQueue.class)).toInstance(QueueFactory.getQueue("import"));
bind(Key.get(Queue.class, MemcacheDeletionQueue.class)).toInstance(
QueueFactory.getQueue("memcache-deletion"));
bind(String.class).annotatedWith(PostCommitTaskUrl.class).toInstance(
WalkaroundServletModule.POST_COMMIT_TASK_PATH);
bind(MessageSerializer.class).to(ServerMessageSerializer.class);
bind(SlobManager.class).to(WaveManager.class);
bind(MutationLog.DeltaEntityConverter.class).to(LegacyDeltaEntityConverter.class);
JsonFlags.bind(binder(), Arrays.asList(FlagName.values()),
binder().getProvider(
Key.get(new TypeLiteral<Map<FlagDeclaration, Object>>() {}, FlagConfiguration.class)));
bindToFlag(Integer.class, PermissionCacheExpirationSeconds.class,
FlagName.ACCESS_CACHE_EXPIRATION_SECONDS);
bindToFlag(String.class, StoreBackendName.class, FlagName.STORE_SERVER);
bindToFlag(Integer.class, StoreBackendInstanceCount.class, FlagName.NUM_STORE_SERVERS);
bindToFlag(Integer.class, SlobChannelExpirationSeconds.class,
FlagName.OBJECT_CHANNEL_EXPIRATION_SECONDS);
bindToFlag(Integer.class, PostCommitActionIntervalMillis.class,
FlagName.POST_COMMIT_ACTION_INTERVAL_MILLIS);
bindToFlag(Integer.class, SlobLocalCacheExpirationMillis.class,
FlagName.SLOB_LOCAL_CACHE_EXPIRATION_MILLIS);
}
@Provides
// The secret is read from the datastore; @Singleton to cache it for
// efficiency. If an admin deletes the secret entity, a new secret will be
// generated, but existing instances will continue to use the old one.
// Re-deploying should fix this since it restarts all instances.
@Singleton
Secret provideSecret(final CheckedDatastore datastore, final Random random)
throws PermanentFailure {
return new RetryHelper().run(
new RetryHelper.Body<Secret>() {
@Override public Secret run() throws RetryableFailure, PermanentFailure {
CheckedTransaction tx = datastore.beginTransaction();
try {
{
Entity e = tx.get(SECRET_KEY);
if (e != null) {
log.info("Using stored secret");
return Secret.of(
DatastoreUtil.getExistingProperty(e, SECRET_PROPERTY, Blob.class).getBytes());
}
}
Secret newSecret = Secret.generate(random);
Entity e = new Entity(SECRET_KEY);
DatastoreUtil.setNonNullUnindexedProperty(e, SECRET_PROPERTY,
new Blob(newSecret.getBytes()));
tx.put(e);
tx.commit();
log.info("Generated new secret");
return newSecret;
} finally {
tx.close();
}
}
});
}
@Provides
@FlagConfiguration
@Singleton
Map<FlagDeclaration, Object> provideFlagConfiguration(@Named("raw flag data") String rawFlagData)
throws FlagFormatException {
return JsonFlags.parse(Arrays.asList(FlagName.values()), rawFlagData);
}
@Provides
@Named("raw flag data")
@Singleton
String provideRawFlagData(@Named("webinf root") String webinfRoot) {
return Util.slurpRequired(webinfRoot + "/flags.json");
}
// TODO(ohler): Make this @Singleton without breaking GuiceSetupTest.
@Provides @Named("buildinfo")
String provideBuildinfo(@Named("webinf root") String webinfRoot) {
return Util.slurpRequired(webinfRoot + "/buildinfo.txt");
}
@Provides
DatastoreService provideDatastore() {
return DatastoreProvider.strongReads();
}
@Provides
MemcacheService provideMemcache() {
return MemcacheServiceFactory.getMemcacheService();
}
@Provides
URLFetchService provideUrlFetchService() {
return URLFetchServiceFactory.getURLFetchService();
}
@Provides
BlobstoreService provideBlobstoreService() {
return BlobstoreServiceFactory.getBlobstoreService();
}
@Provides
BlobInfoFactory provideBlobInfoFactory() {
return new BlobInfoFactory();
}
@Provides
ImagesService provideImagesService() {
return ImagesServiceFactory.getImagesService();
}
@Provides
ChannelService provideChannelService() {
return ChannelServiceFactory.getChannelService();
}
@Provides
UserService provideUserService() {
return UserServiceFactory.getUserService();
}
@Provides
BackendService provideBackendService() {
return BackendServiceFactory.getBackendService();
}
@Provides
SymbolMapsDirectory provideSymbolMapsDir(@Named("webinf root") String webinf) throws IOException {
return new ZipSymbolMapsDirectory(
new JarFile(new File(webinf, "gwt-extra.jar")), "symbolMaps");
}
@Provides @Named("channel api url")
String provideChannelApiUrl() {
return "/_ah/channel/jsapi";
}
}
| 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.server;
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.google.walkaround.proto.ObjectSessionProto;
import com.google.walkaround.proto.gson.ConnectResponseGsonImpl;
import com.google.walkaround.proto.gson.ObjectSessionProtoGsonImpl;
import com.google.walkaround.proto.gson.SignedObjectSessionGsonImpl;
import com.google.walkaround.slob.server.GsonProto;
import com.google.walkaround.slob.server.SlobStore.ConnectResult;
import com.google.walkaround.slob.shared.ClientId;
import com.google.walkaround.slob.shared.MessageException;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.util.server.auth.InvalidSecurityTokenException;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import com.google.walkaround.util.server.servlet.BadRequestException;
import com.google.walkaround.wave.server.auth.XsrfHelper;
import com.google.walkaround.wave.server.auth.XsrfHelper.XsrfTokenExpiredException;
import com.google.walkaround.wave.shared.SharedConstants.Params;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
/**
* Deals with {@link ObjectSession}s: Serializes, parses, signs, verifies.
*
* @author ohler@google.com (Christian Ohler)
*/
public class ObjectSessionHelper {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(ObjectSessionHelper.class.getName());
private final XsrfHelper xsrfHelper;
@Inject
public ObjectSessionHelper(XsrfHelper xsrfHelper) {
this.xsrfHelper = xsrfHelper;
}
private String makeAction(ObjectSessionProto session) {
// If we made sure GSON serialization has the keys in deterministic order,
// we could just serialize the protobuf and use that.
Preconditions.checkArgument(!session.getObjectId().contains(" "),
"Object ID contains a space: %s", session);
Preconditions.checkArgument(!session.getClientId().contains(" "),
"Client ID contains a space: %s", session);
return session.getObjectId() + " " + session.getClientId()
+ " " + session.getStoreType();
}
/**
* Extracts a signed ObjectSession from req, verifies its signature, and
* returns it.
*/
public ObjectSession getVerifiedSession(HttpServletRequest req)
throws InvalidSecurityTokenException, XsrfTokenExpiredException {
String rawSessionString = AbstractHandler.requireParameter(req, Params.SESSION);
log.info("Parsing and verifying signed session " + rawSessionString);
SignedObjectSessionGsonImpl signedSession;
try {
signedSession = GsonProto.fromGson(
new SignedObjectSessionGsonImpl(), rawSessionString);
} catch (MessageException e) {
throw new BadRequestException("Failed to parse signed session", e);
}
xsrfHelper.verify(makeAction(signedSession.getSession()), signedSession.getSignature());
return objectSessionFromProto(signedSession.getSession());
}
public static ObjectSession objectSessionFromProto(ObjectSessionProto proto) {
return new ObjectSession(new SlobId(proto.getObjectId()),
new ClientId(proto.getClientId()),
proto.getStoreType());
}
public static ObjectSessionProto protoFromObjectSession(ObjectSession session) {
ObjectSessionProto proto = new ObjectSessionProtoGsonImpl();
proto.setObjectId(session.getObjectId().getId());
proto.setClientId(session.getClientId().getId());
proto.setStoreType(session.getStoreType());
return proto;
}
private SignedObjectSessionGsonImpl createSignedSession(ObjectSession session) {
ObjectSessionProto proto = protoFromObjectSession(session);
SignedObjectSessionGsonImpl signedSession = new SignedObjectSessionGsonImpl();
signedSession.setSession(proto);
signedSession.setSignature(xsrfHelper.createToken(makeAction(proto)));
return signedSession;
}
/**
* Signs the ObjectSession and puts it in a ConnectResponse together with the
* ConnectResult.
*/
public ConnectResponseGsonImpl createConnectResponse(
ObjectSession session, ConnectResult result) {
ConnectResponseGsonImpl response = new ConnectResponseGsonImpl();
SignedObjectSessionGsonImpl signedSession = createSignedSession(session);
response.setSignedSession(signedSession);
response.setSignedSessionString(GsonProto.toJson(signedSession));
if (result.getChannelToken() != null) {
response.setChannelToken(result.getChannelToken());
}
response.setObjectVersion(result.getVersion());
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.wave.server.gxp;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Objects;
import org.waveprotocol.wave.model.id.WaveletName;
import javax.annotation.Nullable;
/**
* Information {@link ImportOverviewFragment} needs about a wavelet.
*
* @author ohler@google.com (Christian Ohler)
*/
public final class ImportWaveletDisplayRecord {
private final SourceInstance instance;
private final WaveletName waveletName;
private final String linkToOriginal;
private final String creator;
private final String title;
private final String lastModifiedDate;
private final boolean privateImportInProgress;
@Nullable private final String privateImportedSlobId;
@Nullable private final String privateImportedLink;
private final boolean sharedImportInProgress;
@Nullable private final String sharedImportedSlobId;
@Nullable private final String sharedImportedLink;
public ImportWaveletDisplayRecord(SourceInstance instance,
WaveletName waveletName,
String linkToOriginal,
String creator,
String title,
String lastModifiedDate,
boolean privateImportInProgress,
@Nullable String privateImportedSlobId,
@Nullable String privateImportedLink,
boolean sharedImportInProgress,
@Nullable String sharedImportedSlobId,
@Nullable String sharedImportedLink) {
this.instance = checkNotNull(instance, "Null instance");
this.waveletName = checkNotNull(waveletName, "Null waveletName");
this.linkToOriginal = checkNotNull(linkToOriginal, "Null linkToOriginal");
this.creator = checkNotNull(creator, "Null creator");
this.title = checkNotNull(title, "Null title");
this.lastModifiedDate = checkNotNull(lastModifiedDate, "Null lastModifiedDate");
this.privateImportInProgress = privateImportInProgress;
this.privateImportedSlobId = privateImportedSlobId;
this.privateImportedLink = privateImportedLink;
this.sharedImportInProgress = sharedImportInProgress;
this.sharedImportedSlobId = sharedImportedSlobId;
this.sharedImportedLink = sharedImportedLink;
}
public SourceInstance getInstance() {
return instance;
}
public WaveletName getWaveletName() {
return waveletName;
}
public String getLinkToOriginal() {
return linkToOriginal;
}
public String getCreator() {
return creator;
}
public String getTitle() {
return title;
}
public String getLastModifiedDate() {
return lastModifiedDate;
}
public boolean isPrivateImportInProgress() {
return privateImportInProgress;
}
@Nullable public String getPrivateImportedSlobId() {
return privateImportedSlobId;
}
@Nullable public String getPrivateImportedLink() {
return privateImportedLink;
}
public boolean isSharedImportInProgress() {
return sharedImportInProgress;
}
@Nullable public String getSharedImportedSlobId() {
return sharedImportedSlobId;
}
@Nullable public String getSharedImportedLink() {
return sharedImportedLink;
}
@Override public String toString() {
return getClass().getSimpleName() + "("
+ instance + ", "
+ waveletName + ", "
+ linkToOriginal + ", "
+ creator + ", "
+ title + ", "
+ lastModifiedDate + ", "
+ privateImportInProgress + ", "
+ privateImportedSlobId + ", "
+ privateImportedLink + ", "
+ sharedImportInProgress + ", "
+ sharedImportedSlobId + ", "
+ sharedImportedLink
+ ")";
}
@Override public final boolean equals(Object o) {
if (o == this) { return true; }
if (!(o instanceof ImportWaveletDisplayRecord)) { return false; }
ImportWaveletDisplayRecord other = (ImportWaveletDisplayRecord) o;
return privateImportInProgress == other.privateImportInProgress
&& sharedImportInProgress == other.sharedImportInProgress
&& Objects.equal(instance, other.instance)
&& Objects.equal(waveletName, other.waveletName)
&& Objects.equal(linkToOriginal, other.linkToOriginal)
&& Objects.equal(creator, other.creator)
&& Objects.equal(title, other.title)
&& Objects.equal(lastModifiedDate, other.lastModifiedDate)
&& Objects.equal(privateImportedSlobId, other.privateImportedSlobId)
&& Objects.equal(privateImportedLink, other.privateImportedLink)
&& Objects.equal(sharedImportedSlobId, other.sharedImportedSlobId)
&& Objects.equal(sharedImportedLink, other.sharedImportedLink);
}
@Override public final int hashCode() {
return Objects.hashCode(instance, waveletName, linkToOriginal, creator, title, lastModifiedDate,
privateImportInProgress, privateImportedSlobId, privateImportedLink,
sharedImportInProgress, sharedImportedSlobId, sharedImportedLink);
}
}
| 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.server.gxp;
import org.waveprotocol.wave.model.id.WaveId;
import java.util.List;
/**
* A wave instance to import from.
*
* @author ohler@google.com (Christian Ohler)
*/
public interface SourceInstance {
interface Factory {
List<? extends SourceInstance> getInstances();
/**
* @throws RuntimeException (or a subtype) if {@code serialized} is not a
* serialized {@code SourceInstance}.
*/
SourceInstance parseUnchecked(String serialized);
}
String serialize();
/** URL for Active Robot API calls. */
String getApiUrl();
/** Short name for display. */
String getShortName();
/** Long name for display. */
String getLongName();
/** Returns a link to a wave on this instance. */
String getWaveLink(WaveId waveId);
/**
* Returns the URL of an attachment on this instance given the attachment path from the attachment
* data document.
*/
String getFullAttachmentUrl(String attachmentPath);
}
| 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.server.gxp;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
/**
* Information {@link FlagsFragment} needs about a flag.
*
* @author ohler@google.com (Christian Ohler)
*/
public final class FlagDisplayRecord {
private final String name;
private final String type;
private final String value;
public FlagDisplayRecord(String name, String type, String value) {
Preconditions.checkNotNull(name, "Null name");
Preconditions.checkNotNull(type, "Null type");
Preconditions.checkNotNull(value, "Null value");
this.name = name;
this.type = type;
this.value = value;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public String getValue() {
return value;
}
@Override public String toString() {
return "FlagDisplayRecord(" + name + ", " + type + ", " + value + ")";
}
@Override public final boolean equals(Object o) {
if (o == this) { return true; }
if (!(o instanceof FlagDisplayRecord)) { return false; }
FlagDisplayRecord other = (FlagDisplayRecord) o;
return Objects.equal(name, other.name)
&& Objects.equal(type, other.type)
&& Objects.equal(value, other.value);
}
@Override public final int hashCode() {
return Objects.hashCode(name, type, 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.wave.server.gxp;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Information {@link InboxFragment} needs about a wave.
*
* @author ohler@google.com (Christian Ohler)
*/
public class InboxDisplayRecord {
private final String creator;
private final String title;
private final String snippet;
private final String lastModified;
private final String link;
public InboxDisplayRecord(String creator,
String title,
String snippet,
String lastModified,
String link) {
this.creator = checkNotNull(creator, "Null creator");
this.title = checkNotNull(title, "Null title");
this.snippet = checkNotNull(snippet, "Null snippet");
this.lastModified = checkNotNull(lastModified, "Null lastModified");
this.link = checkNotNull(link, "Null link");
}
public String getCreator() {
return creator;
}
public String getTitle() {
return title;
}
public String getSnippet() {
return snippet;
}
public String getLastModified() {
return lastModified;
}
public String getLink() {
return link;
}
@Override public String toString() {
return "InboxDisplayRecord("
+ creator + ", "
+ title + ", "
+ snippet + ", "
+ lastModified + ", "
+ link
+ ")";
}
}
| 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.server;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceConfig;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.ImplicitTransactionManagementPolicy;
import com.google.appengine.api.datastore.ReadPolicy;
import com.google.appengine.api.utils.SystemProperty;
import com.google.apphosting.api.ApiProxy;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Provides datastore instance to use.
*
* @author ohler@google.com (Christian Ohler)
*/
public class DatastoreProvider {
private DatastoreProvider() {}
private static final DatastoreService STRONG_READS =
DatastoreServiceFactory.getDatastoreService(DatastoreServiceConfig.Builder
.withDeadline(5 /*seconds*/)
.implicitTransactionManagementPolicy(ImplicitTransactionManagementPolicy.NONE)
.readPolicy(new ReadPolicy(ReadPolicy.Consistency.STRONG)));
private static final DatastoreService EVENTUAL_READS =
DatastoreServiceFactory.getDatastoreService(DatastoreServiceConfig.Builder
.withDeadline(5 /*seconds*/)
.implicitTransactionManagementPolicy(ImplicitTransactionManagementPolicy.NONE)
.readPolicy(new ReadPolicy(ReadPolicy.Consistency.EVENTUAL)));
public static DatastoreService strongReads() {
return STRONG_READS;
}
public static DatastoreService eventualReads() {
return EVENTUAL_READS;
}
}
| 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.server.admin;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.gxp.base.GxpContext;
import com.google.gxp.html.HtmlClosure;
import com.google.inject.Inject;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import com.google.walkaround.util.server.servlet.BadRequestException;
import com.google.walkaround.wave.server.Flag;
import com.google.walkaround.wave.server.FlagName;
import com.google.walkaround.wave.server.gxp.Admin;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Serves a page that has a few options for admins.
*
* @author ohler@google.com (Christian Ohler)
*/
public class AdminHandler extends AbstractHandler {
private static final HtmlClosure EMPTY_CONTENT = new HtmlClosure() {
@Override public void write(Appendable out, GxpContext gxpContext) { }
};
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(AdminHandler.class.getName());
@Inject UserService userService;
@Inject User user;
@Inject @Flag(FlagName.ANALYTICS_ACCOUNT) String analyticsAccount;
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
log.warning("Admin page requested by " + user.getEmail());
if (!userService.isUserAdmin()) {
log.severe("Admin page requested by non-admin user!");
throw new BadRequestException();
}
resp.setContentType("text/html");
Admin.write(resp.getWriter(), new GxpContext(req.getLocale()),
analyticsAccount, EMPTY_CONTENT);
}
}
| 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.server.admin;
import com.google.common.collect.Lists;
import com.google.gxp.base.GxpContext;
import com.google.gxp.html.HtmlClosure;
import com.google.inject.Inject;
import com.google.walkaround.slob.server.MutationLog;
import com.google.walkaround.slob.server.SlobStoreSelector;
import com.google.walkaround.slob.server.MutationLog.DeltaIterator;
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;
import com.google.walkaround.util.server.appengine.CheckedDatastore.CheckedTransaction;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import com.google.walkaround.util.server.servlet.BadRequestException;
import com.google.walkaround.wave.server.Flag;
import com.google.walkaround.wave.server.FlagName;
import com.google.walkaround.wave.server.StoreType;
import com.google.walkaround.wave.server.gxp.Admin;
import com.google.walkaround.wave.server.gxp.StoreViewFragment;
import org.waveprotocol.wave.model.util.Pair;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author danilatos@google.com (Daniel Danilatos)
* @author ohler@google.com (Christian Ohler)
*/
public class StoreViewHandler extends AbstractHandler {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(StoreViewHandler.class.getName());
@Inject CheckedDatastore datastore;
@Inject SlobStoreSelector storeSelector;
@Inject @Flag(FlagName.ANALYTICS_ACCOUNT) String analyticsAccount;
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String storeType = optionalParameter(req, "storeType", "Wavelet");
String id = optionalParameter(req, "id", "");
String snapshotVersion = optionalParameter(req, "snapshotVersion", "");
String historyStart = optionalParameter(req, "historyStart", "0");
String historyEnd = optionalParameter(req, "historyEnd", "");
@Nullable Long objectVersion = null;
List<Pair<Long, String>> items = Lists.newArrayList();
String snapshot = "";
if (!id.isEmpty()) {
try {
SlobId objectId = new SlobId(id);
CheckedTransaction tx = datastore.beginTransaction();
try {
MutationLog mutationLog = storeSelector.get(storeType).getMutationLogFactory()
.create(tx, objectId);
objectVersion = mutationLog.getVersion();
if (!historyStart.isEmpty()) {
long start = Long.parseLong(historyStart);
DeltaIterator it = mutationLog.forwardHistory(start,
historyEnd.isEmpty() ? start + 1000 : Long.parseLong(historyEnd));
for (long version = start; it.hasNext(); version++) {
items.add(Pair.of(version, "" + it.next()));
}
}
if (!snapshotVersion.isEmpty()) {
snapshot = mutationLog.reconstruct(Long.parseLong(snapshotVersion))
.getState().snapshot();
}
} finally {
tx.rollback();
}
} catch (NumberFormatException e) {
throw new BadRequestException(e);
} catch (PermanentFailure e) {
throw new IOException(e);
} catch (RetryableFailure e) {
throw new IOException(e);
}
}
HtmlClosure content = StoreViewFragment.getGxpClosure(
storeType, id, objectVersion == null ? "" : ("" + objectVersion),
historyStart, historyEnd, items, snapshotVersion, snapshot);
resp.setContentType("text/html");
Admin.write(resp.getWriter(), new GxpContext(req.getLocale()),
analyticsAccount, content);
}
}
| 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.server.admin;
import com.google.common.collect.Lists;
import com.google.gxp.base.GxpContext;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import com.google.walkaround.util.server.flags.FlagDeclaration;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import com.google.walkaround.wave.server.Flag;
import com.google.walkaround.wave.server.FlagConfiguration;
import com.google.walkaround.wave.server.FlagName;
import com.google.walkaround.wave.server.gxp.Admin;
import com.google.walkaround.wave.server.gxp.FlagDisplayRecord;
import com.google.walkaround.wave.server.gxp.FlagsFragment;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author ohler@google.com (Christian Ohler)
*/
public class FlagsHandler extends AbstractHandler {
@Inject @Named("raw flag data") String rawFlags;
@Inject @FlagConfiguration Map<FlagDeclaration, Object> parsedFlags;
@Inject @Flag(FlagName.ANALYTICS_ACCOUNT) String analyticsAccount;
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
List<FlagDisplayRecord> records = Lists.newArrayListWithCapacity(parsedFlags.size());
for (Map.Entry<FlagDeclaration, Object> e : parsedFlags.entrySet()) {
records.add(new FlagDisplayRecord(e.getKey().getName(),
"" + e.getKey().getType().getName(),
"" + e.getValue()));
}
Collections.sort(records,
new Comparator<FlagDisplayRecord>() {
@Override public int compare(FlagDisplayRecord a, FlagDisplayRecord b) {
return a.getName().compareTo(b.getName());
}
});
resp.setContentType("text/html");
Admin.write(resp.getWriter(), new GxpContext(req.getLocale()),
analyticsAccount, FlagsFragment.getGxpClosure(records, rawFlags));
}
}
| 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.server.admin;
import com.google.gxp.base.GxpContext;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import com.google.walkaround.wave.server.Flag;
import com.google.walkaround.wave.server.FlagName;
import com.google.walkaround.wave.server.gxp.Admin;
import com.google.walkaround.wave.server.gxp.BuildinfoFragment;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Serves a page with build information.
*
* @author ohler@google.com (Christian Ohler)
*/
public class BuildinfoHandler extends AbstractHandler {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(BuildinfoHandler.class.getName());
@Inject @Named("buildinfo") private String buildinfo;
@Inject @Flag(FlagName.ANALYTICS_ACCOUNT) String analyticsAccount;
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/html");
Admin.write(resp.getWriter(), new GxpContext(req.getLocale()),
analyticsAccount, BuildinfoFragment.getGxpClosure(buildinfo));
}
}
| 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.server.admin;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.users.User;
import com.google.inject.Inject;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Clears memcache. Should only be exposed to admin users.
*
* @author ohler@google.com (Christian Ohler)
*/
public class ClearMemcacheHandler extends AbstractHandler {
private final MemcacheService memcache;
private final User user;
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(ClearMemcacheHandler.class.getName());
@Inject
public ClearMemcacheHandler(MemcacheService memcache, User user) {
this.memcache = memcache;
this.user = user;
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
log.warning("Memcache clear requested by " + user.getEmail());
memcache.clearAll();
log.warning("Memcache cleared");
resp.setContentType("text/plain");
resp.getWriter().println("Memcache cleared, " + user.getEmail());
}
}
| 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.server;
/**
* @author danilatos@google.com (Daniel Danilatos)
*/
public class DefaultServletConfig extends ServletConfig {
static {
GuiceSetup.addExtraModule(new DefaultModule());
}
}
| 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.server.auth;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Objects;
import java.io.Serializable;
/**
* A stable user identifier: a string that uniquely identifies a user and
* remains the same even if e.g. the e-mail address changes, and will not be
* re-used even if an account is deleted.
*
* @author ohler@google.com (Christian Ohler)
*/
public class StableUserId implements Serializable {
private static final long serialVersionUID = 496823047858055085L;
private final String id;
public StableUserId(String id) {
this.id = checkNotNull(id, "Null id");
}
public String getId() {
return id;
}
@Override public String toString() {
return "StableUserId(" + id + ")";
}
@Override public final boolean equals(Object o) {
if (o == this) { return true; }
if (!(o instanceof StableUserId)) { return false; }
StableUserId other = (StableUserId) 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.wave.server.auth;
import com.google.appengine.api.users.User;
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.api.client.googleapis.auth.oauth2.draft10.GoogleAuthorizationRequestUrl;
import com.google.inject.BindingAnnotation;
import com.google.inject.Inject;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import com.google.walkaround.wave.server.Flag;
import com.google.walkaround.wave.server.FlagName;
import com.google.walkaround.wave.server.gxp.Auth;
import com.google.walkaround.wave.server.servlet.PageSkinWriter;
import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Shows the "enable wave" page.
*
* @author ohler@google.com (Christian Ohler)
*/
public class OAuthInterstitialHandler extends AbstractHandler {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(OAuthInterstitialHandler.class.getName());
/** Binding annotation for the OAuth callback URL path. */
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface CallbackPath { }
/** Binding annotation for the OAuth scopes. */
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface Scopes { }
@Inject @Flag(FlagName.OAUTH_CLIENT_ID) String clientId;
@Inject @CallbackPath String callbackPath;
@Inject @Scopes String oAuthScopes;
@Inject PageSkinWriter pageSkinWriter;
@Inject User user;
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String userEmail = user.getEmail();
String originalRequest = requireParameter(req, "originalRequest");
String authorizeUrl =
new GoogleAuthorizationRequestUrl(clientId, callbackPath, oAuthScopes).build()
// TODO(ohler): Find out if GoogleAuthorizationRequestUrl offers an API
// to do this rather than appending the literal string. Also consider
// using server-side auto-approval rather than offline access ("perform
// these operations when I'm not using the application") since that's
// scary -- but import is meant to be able to run in the background over
// a few hours, so maybe we do need it.
// http://googlecode.blogspot.com/2011/10/upcoming-changes-to-oauth-20-endpoint.html
// has more details.
+ "&access_type=offline&approval_prompt=force";
log.info("userEmail=" + userEmail
+ ", originalRequest=" + originalRequest
+ ", authorizeUrl=" + authorizeUrl);
resp.setContentType("text/html");
resp.setCharacterEncoding("UTF-8");
pageSkinWriter.write("Enable walkaround", userEmail,
Auth.getGxpClosure(authorizeUrl, originalRequest, userEmail));
}
}
| 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.server.auth;
import com.google.common.base.Preconditions;
import com.google.inject.servlet.RequestScoped;
import org.waveprotocol.wave.model.wave.ParticipantId;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Holds information about the user we are acting as. Many helper classes
* receive a {@code UserContext} for making OAuth requests or for attributing
* actions (for example, incoming deltas) to the current user.
*
* For each request, this starts out unintialized, since we have no uniform way
* of identifying the user. Authentication filters like
* {@link InteractiveAuthFilter} and {@link RpcAuthFilter} implement different
* means of identifying the user and populate the {@code UserContext}
* accordingly, including reading OAuth credentials from persistent storage.
*
* Servlets like {@link OAuthCallbackHandler} that need to manipulate
* credentials in special ways populate the {@link UserContext} directly.
*
* Attempting to call a getter method while the corresponding information is not
* present will result in an exception. This makes it easy to tell when
* a servlet is not using the right authentication filter.
*
* This class is not thread-safe; if we ever use more than one thread for a
* single request, we'll have to think about thread safety.
*
* This class is structurally similar to {@link AccountStore.Record} but plays a
* very different role -- {@code UserContext} is mutable to allow authentication
* filters (and other classes that handle login) to pass information about the
* current user to other classes that need it, while {@code AccountStore.Record}
* is an immutable in-memory representation of a record in {@link AccountStore}.
*
* @author ohler@google.com (Christian Ohler)
*/
@RequestScoped
public class UserContext {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(UserContext.class.getName());
// At some point, we might want to refactor this to allow the auth filters to
// perform retrieval of the OAuth credentials lazily -- many servlets don't
// need credentials (or need them only in some cases), and the redundant
// datastore read is undesirable. However, since we cache credentials in
// memcache, we typically merely do a redundant memcache lookup, which is not
// a big problem. So implementing this laziness is not urgent.
@Nullable private StableUserId userId = null;
@Nullable private ParticipantId participantId = null;
@Nullable private OAuthCredentials oAuthCredentials = null;
public UserContext() {
}
public boolean hasUserId() {
return userId != null;
}
public StableUserId getUserId() {
Preconditions.checkState(hasUserId(), "No userId: %s", this);
return userId;
}
public UserContext setUserId(@Nullable StableUserId userId) {
this.userId = userId;
return this;
}
public boolean hasParticipantId() {
return participantId != null;
}
public ParticipantId getParticipantId() {
Preconditions.checkState(hasParticipantId(), "No participantId: %s", this);
return participantId;
}
public UserContext setParticipantId(@Nullable ParticipantId participantId) {
this.participantId = participantId;
return this;
}
public boolean hasOAuthCredentials() {
return oAuthCredentials != null;
}
public OAuthCredentials getOAuthCredentials() {
Preconditions.checkState(hasOAuthCredentials(), "No oAuthCredentials: %s", this);
return oAuthCredentials;
}
public UserContext setOAuthCredentials(@Nullable OAuthCredentials oAuthCredentials) {
this.oAuthCredentials = oAuthCredentials;
return this;
}
@Override public String toString() {
return "UserContext("
+ userId + ", "
+ participantId + ", "
+ oAuthCredentials
+ ")";
}
}
| 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.server.auth;
import static com.google.common.base.Preconditions.checkNotNull;
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.appengine.api.datastore.Query.FilterOperator;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
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.CheckedPreparedQuery;
import com.google.walkaround.util.server.appengine.CheckedDatastore.CheckedTransaction;
import com.google.walkaround.util.server.appengine.DatastoreUtil;
import com.google.walkaround.util.server.appengine.MemcacheTable;
import com.google.walkaround.util.server.appengine.MemcacheTable.IdentifiableValue;
import org.waveprotocol.wave.model.wave.ParticipantId;
import java.io.Serializable;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Stores user account information.
*
* @author ohler@google.com (Christian Ohler)
* @author danilatos@google.com (Daniel Danilatos)
*/
public class AccountStore {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(AccountStore.class.getName());
/**
* Information about a user stored in {@link AccountStore}.
*/
public static final class Record implements Serializable {
private static final long serialVersionUID = 759933263092669762L;
private final StableUserId userId;
private final ParticipantId participantId;
@Nullable private final OAuthCredentials oAuthCredentials;
public Record(StableUserId userId,
ParticipantId participantId,
@Nullable OAuthCredentials oAuthCredentials) {
this.userId = checkNotNull(userId, "Null userId");
this.participantId = checkNotNull(participantId, "Null participantId");
this.oAuthCredentials = oAuthCredentials;
}
public StableUserId getUserId() {
return userId;
}
public ParticipantId getParticipantId() {
return participantId;
}
@Nullable public OAuthCredentials getOAuthCredentials() {
return oAuthCredentials;
}
@Override public String toString() {
return "Record(" + userId + ", " + participantId + ", " + oAuthCredentials + ")";
}
@Override public final boolean equals(Object o) {
if (o == this) { return true; }
if (!(o instanceof Record)) { return false; }
Record other = (Record) o;
return Objects.equal(userId, other.userId)
&& Objects.equal(participantId, other.participantId)
&& Objects.equal(oAuthCredentials, other.oAuthCredentials);
}
@Override public final int hashCode() {
return Objects.hashCode(userId, participantId, oAuthCredentials);
}
}
// Incremented to 2 because user ids have changed.
private static final String ENTRY_KIND = "AccountRecord2";
// TODO(ohler): The user id is already in the key, remove the property.
private static final String STABLE_USER_ID_PROPERTY = "UserId";
private static final String USER_EMAIL_PROPERTY = "UserEmail";
private static final String REFRESH_TOKEN_PROPERTY = "RefreshToken";
private static final String ACCESS_TOKEN_PROPERTY = "AccessToken";
private static final String MEMCACHE_TAG = "AccountStore";
private final CheckedDatastore datastore;
private final MemcacheTable<StableUserId, Record> memcache;
@Inject
public AccountStore(CheckedDatastore datastore, MemcacheTable.Factory memcacheFactory) {
this.datastore = datastore;
this.memcache = memcacheFactory.create(MEMCACHE_TAG);
}
private static Key makeKey(StableUserId userId) {
return KeyFactory.createKey(ENTRY_KIND, "u" + userId.getId());
}
public void put(final Record record) throws PermanentFailure {
Preconditions.checkNotNull(record, "Null record");
log.info("Putting record " + record);
final StableUserId userId = record.getUserId();
ParticipantId participantId = record.getParticipantId();
OAuthCredentials credentials = record.getOAuthCredentials();
String refreshToken = credentials == null ? null : credentials.getRefreshToken();
String accessToken = credentials == null ? null : credentials.getAccessToken();
final Entity entity = new Entity(makeKey(userId));
DatastoreUtil.setNonNullIndexedProperty(entity, STABLE_USER_ID_PROPERTY, userId.getId());
DatastoreUtil.setNonNullIndexedProperty(
entity, USER_EMAIL_PROPERTY, participantId.getAddress());
DatastoreUtil.setOrRemoveUnindexedProperty(entity, REFRESH_TOKEN_PROPERTY, refreshToken);
DatastoreUtil.setOrRemoveUnindexedProperty(entity, ACCESS_TOKEN_PROPERTY, accessToken);
new RetryHelper().run(new RetryHelper.VoidBody() {
@Override public void run() throws RetryableFailure, PermanentFailure {
CheckedTransaction tx = datastore.beginTransaction();
log.info("About to put " + entity);
tx.put(entity);
memcache.enqueuePutNull(tx, userId);
tx.commit();
log.info("Committed " + tx);
}
});
memcache.delete(userId);
}
public void delete(final StableUserId userId) throws PermanentFailure {
Preconditions.checkNotNull(userId, "Null userId");
log.info("Deleting record for user " + userId);
final Key key = makeKey(userId);
new RetryHelper().run(new RetryHelper.VoidBody() {
@Override public void run() throws RetryableFailure, PermanentFailure {
CheckedTransaction tx = datastore.beginTransaction();
log.info("About to delete " + key);
tx.delete(key);
memcache.enqueuePutNull(tx, userId);
tx.commit();
log.info("Committed " + tx);
}
});
memcache.delete(userId);
}
@Nullable private Record convertEntity(@Nullable Entity e) {
if (e == null) {
return null;
} else if (e.hasProperty(REFRESH_TOKEN_PROPERTY)) {
return new Record(
new StableUserId(
DatastoreUtil.getExistingProperty(e, STABLE_USER_ID_PROPERTY, String.class)),
ParticipantId.ofUnsafe(
DatastoreUtil.getExistingProperty(e, USER_EMAIL_PROPERTY, String.class)),
new OAuthCredentials(
DatastoreUtil.getExistingProperty(e, REFRESH_TOKEN_PROPERTY, String.class),
DatastoreUtil.getExistingProperty(e, ACCESS_TOKEN_PROPERTY, String.class)));
} else {
return new Record(
new StableUserId(
DatastoreUtil.getExistingProperty(e, STABLE_USER_ID_PROPERTY, String.class)),
ParticipantId.ofUnsafe(
DatastoreUtil.getExistingProperty(e, USER_EMAIL_PROPERTY, String.class)),
null);
}
}
@Nullable public Record get(final StableUserId userId) throws PermanentFailure {
Preconditions.checkNotNull(userId, "Null userId");
IdentifiableValue<Record> cached = memcache.getIdentifiable(userId);
if (cached != null && cached.getValue() != null) {
log.info("Account record found in cache: " + cached);
return cached.getValue();
}
log.info("Fetching user credentials for user " + userId);
Entity e = new RetryHelper().run(
new RetryHelper.Body<Entity>() {
@Override public Entity run() throws RetryableFailure, PermanentFailure {
CheckedTransaction tx = datastore.beginTransaction();
try {
Entity entity = tx.get(makeKey(userId));
log.info("Got " + (entity == null ? null : entity.getKey()));
return entity;
} finally {
tx.rollback();
}
}
});
Record read = convertEntity(e);
memcache.putIfUntouched(userId, cached, read);
return read;
}
/**
* Returns info for the given e-mail, or null if not found. Note that this
* datastore read is only eventually consistent, so this method may return
* null for a short while after a record for this user has been stored.
*/
@Nullable public Record findByEmail(final String userEmail) throws PermanentFailure {
Preconditions.checkNotNull(userEmail, "Null email");
log.info("Fetching user credentials for email " + userEmail);
Entity e = new RetryHelper().run(
new RetryHelper.Body<Entity>() {
@Override public Entity run() throws RetryableFailure, PermanentFailure {
CheckedPreparedQuery q = datastore.prepareNontransactionalQuery(
new Query(ENTRY_KIND).addFilter(
USER_EMAIL_PROPERTY, FilterOperator.EQUAL, userEmail));
return q.asSingleEntity();
}
});
return convertEntity(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.wave.server.auth;
import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse;
import com.google.api.client.extensions.appengine.http.urlfetch.UrlFetchTransport;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessTokenRequest.GoogleAuthorizationCodeGrant;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.appengine.api.users.User;
import com.google.common.net.UriEscapers;
import com.google.gxp.base.GxpContext;
import com.google.inject.Inject;
import com.google.walkaround.util.server.RetryHelper.PermanentFailure;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import com.google.walkaround.wave.server.Flag;
import com.google.walkaround.wave.server.FlagName;
import com.google.walkaround.wave.server.auth.OAuthInterstitialHandler.CallbackPath;
import com.google.walkaround.wave.server.gxp.AuthPopup;
import org.waveprotocol.wave.model.wave.ParticipantId;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Handles the callback in the OAuth flow.
*
* @author danilatos@google.com (Daniel Danilatos)
* @author ohler@google.com (Christian Ohler)
*/
public class OAuthCallbackHandler extends AbstractHandler {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(OAuthCallbackHandler.class.getName());
@Inject AccountStore accountStore;
@Inject UserContext userContext;
@Inject @CallbackPath String callbackUrl;
@Inject @Flag(FlagName.OAUTH_CLIENT_ID) String clientId;
@Inject @Flag(FlagName.OAUTH_CLIENT_SECRET) String clientSecret;
@Inject User user;
@Inject @Flag(FlagName.ANALYTICS_ACCOUNT) String analyticsAccount;
private void writeAccountRecordFromContext() throws IOException {
try {
accountStore.put(
new AccountStore.Record(userContext.getUserId(), userContext.getParticipantId(),
userContext.getOAuthCredentials()));
} catch (PermanentFailure e) {
throw new IOException("Failed to write account record", e);
}
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String errorCode = req.getParameter("error");
if (errorCode != null) {
String errorDescription = req.getParameter("error_description");
log.info("error: " + errorCode + ", description: " + errorDescription);
String errorMessage;
if ("access_denied".equals(errorCode)) {
errorMessage = "To enable these features, please click enable, then allow access.";
} else {
errorMessage = "An error occured (" + errorCode + "): " + errorDescription;
}
log.info("errorMessage=" + errorMessage);
writeRegularError(req, resp, errorMessage);
return;
}
String code = requireParameter(req, "code");
log.info("code=" + code);
log.info("clientId=" + clientId + ", clientSecret=" + clientSecret + ", code=" + code
+ ", callbackUrl=" + callbackUrl);
GoogleAuthorizationCodeGrant authRequest = new GoogleAuthorizationCodeGrant(
new UrlFetchTransport(), new JacksonFactory(), clientId, clientSecret, code, callbackUrl);
AccessTokenResponse authResponse;
try {
authResponse = authRequest.execute();
} catch (IOException e) {
log.log(Level.WARNING, "Failed attempt, trying again", e);
if (e instanceof HttpResponseException) {
HttpResponseException f = (HttpResponseException) e;
ByteArrayOutputStream o = new ByteArrayOutputStream();
f.getResponse().getRequest().getContent().writeTo(o);
// TODO(ohler): Use correct character set.
log.warning("content of rejected request: " + o.toString());
log.warning("rejection response body: " + f.getResponse().parseAsString());
}
resp.sendRedirect(req.getRequestURI() + "?code=" + urlEncode(code) + "&tryagain=true");
return;
}
String refreshToken = authResponse.refreshToken;
String accessToken = authResponse.accessToken;
if (refreshToken == null) {
writeRegularError(req, resp, "Error gaining authorization: no refresh token");
return;
}
if (accessToken == null) {
writeRegularError(req, resp, "Error gaining authorization: no access token");
return;
}
// TODO(ohler): Disable user switching in OAuth dialog once Google's OAuth
// API supports that. (We don't need to be too defensive about account
// mismatches since there's no real harm in allowing a user to use another
// Google account for contact information and to import waves from; but it
// is confusing, so we should disable it.)
userContext.setOAuthCredentials(new OAuthCredentials(refreshToken, accessToken));
userContext.setUserId(new StableUserId(user.getUserId()));
userContext.setParticipantId(ParticipantId.ofUnsafe(user.getEmail()));
log.info("User context: " + userContext);
writeAccountRecordFromContext();
resp.setContentType("text/html");
resp.setCharacterEncoding("UTF-8");
AuthPopup.write(resp.getWriter(), new GxpContext(req.getLocale()),
analyticsAccount, null);
}
private void writeRegularError(HttpServletRequest req, HttpServletResponse resp,
String errorMessage) throws IOException {
resp.setContentType("text/html");
resp.setCharacterEncoding("UTF-8");
AuthPopup.write(resp.getWriter(), new GxpContext(req.getLocale()),
analyticsAccount, errorMessage);
}
private String urlEncode(String s) {
return UriEscapers.uriQueryStringEscaper(false).escape(s);
}
}
| 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.server.auth;
import com.google.appengine.api.users.UserService;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.walkaround.wave.server.auth.ServletAuthHelper.UserServiceAccountLookup;
import com.google.walkaround.wave.shared.SharedConstants;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Filter that initializes {@link UserContext} from App Engine's
* {@link UserService}. Leaves the OAuth credentials in {@link UserContext} null if no
* OAuth token is stored for the user.
*
* @author ohler@google.com (Christian Ohler)
*/
@Singleton
public class RpcAuthFilter implements Filter {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(RpcAuthFilter.class.getName());
private final Provider<UserServiceAccountLookup> accountLookup;
private final Provider<ServletAuthHelper> helper;
@Inject
public RpcAuthFilter(Provider<UserServiceAccountLookup> accountLookup,
Provider<ServletAuthHelper> helper) {
this.accountLookup = accountLookup;
this.helper = helper;
}
@Override
public void init(FilterConfig config) {}
@Override
public void destroy() {}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
final HttpServletRequest req = (HttpServletRequest) request;
final HttpServletResponse resp = (HttpServletResponse) response;
helper.get().filter(req, resp, filterChain, accountLookup.get(),
new ServletAuthHelper.NeedNewOAuthTokenHandler() {
@Override public void sendNeedTokenResponse() throws IOException {
resp.setStatus(HttpServletResponse.SC_OK);
// TODO(ohler): Define a proper protocol between this and AjaxRpc. For now,
// it treats any parse error as "need new token", so producing something
// that is not valid json is enough.
resp.setContentType("application/json");
resp.setCharacterEncoding("UTF-8");
resp.getWriter().write(SharedConstants.XSSI_PREFIX + "need new OAuth token");
}
});
}
}
| 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.server.auth;
import com.google.api.client.extensions.appengine.http.urlfetch.UrlFetchTransport;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.inject.Inject;
import com.google.walkaround.wave.server.Flag;
import com.google.walkaround.wave.server.FlagName;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Helper for making OAuth2 requests.
*
* @author danilatos@google.com (Daniel Danilatos)
* @author ohler@google.com (Christian Ohler)
*/
public class OAuthRequestHelper {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(OAuthRequestHelper.class.getName());
private final UserContext userContext;
private final GoogleAccessProtectedResource accessThing;
@Inject
public OAuthRequestHelper(
@Flag(FlagName.OAUTH_CLIENT_ID) String clientId,
@Flag(FlagName.OAUTH_CLIENT_SECRET) String clientSecret,
UserContext userContext) {
this.userContext = userContext;
this.accessThing = new GoogleAccessProtectedResource(
getCredentials().getAccessToken(),
new UrlFetchTransport(), new JacksonFactory(), clientId, clientSecret,
getCredentials().getRefreshToken());
}
private OAuthCredentials getCredentials() {
return userContext.getOAuthCredentials();
}
public String getAuthorizationHeaderValue() {
return "OAuth " + getCredentials().getAccessToken();
}
public void authorize(HTTPRequest req) {
req.setHeader(new HTTPHeader("Authorization", getAuthorizationHeaderValue()));
}
public void refreshToken() throws IOException {
OAuthCredentials oldCredentials = getCredentials();
log.info("Trying to refresh token; credentials: " + oldCredentials);
if (!accessThing.refreshToken()) {
log.log(Level.WARNING, "refreshToken() returned false; perhaps revoked");
throw new NeedNewOAuthTokenException("refreshToken() returned false; perhaps revoked");
}
String newAccessToken = accessThing.getAccessToken();
String newRefreshToken = accessThing.getRefreshToken();
log.info("New access token: " + newAccessToken);
if (newAccessToken == null) {
throw new RuntimeException("No access token provided after refresh");
}
if (!oldCredentials.getRefreshToken().equals(newRefreshToken)) {
throw new AssertionError("Unexpectedly got a different refresh token: " + newRefreshToken
+ ", had " + oldCredentials.getRefreshToken());
}
userContext.setOAuthCredentials(new OAuthCredentials(newRefreshToken, newAccessToken));
log.info("Successfully refreshed token: " + userContext);
}
}
| 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.server.auth;
import com.google.appengine.api.urlfetch.HTTPHeader;
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.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.inject.Inject;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;
/**
* A fetch service that signs fetch requests with OAuth2.
*
* @author hearnden@google.com (David Hearnden)
* @author ohler@google.com (Christian Ohler)
*/
public final class OAuthedFetchService {
/**
* Detects whether an HTTP response indicates that the OAuth token has
* expired.
*/
public interface TokenRefreshNeededDetector {
boolean refreshNeeded(HTTPResponse resp) throws IOException;
}
public static final TokenRefreshNeededDetector RESPONSE_CODE_401_DETECTOR =
new TokenRefreshNeededDetector() {
@Override public boolean refreshNeeded(HTTPResponse resp) {
return resp.getResponseCode() == 401;
}
};
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(OAuthedFetchService.class.getName());
private final URLFetchService fetch;
private final OAuthRequestHelper helper;
@Inject
public OAuthedFetchService(URLFetchService fetch, OAuthRequestHelper helper) {
this.fetch = fetch;
this.helper = helper;
}
private String describeRequest(HTTPRequest req) {
StringBuilder b = new StringBuilder(req.getMethod() + " " + req.getURL());
for (HTTPHeader h : req.getHeaders()) {
b.append("\n" + h.getName() + ": " + h.getValue());
}
return "" + b;
}
private String describeResponse(HTTPResponse resp, boolean includeBody) {
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());
}
if (includeBody) {
b.append("\n" + new String(resp.getContent(), Charsets.UTF_8));
} else {
b.append("\n<content elided>");
}
return "" + b;
}
private HTTPResponse fetch1(HTTPRequest req, TokenRefreshNeededDetector refreshNeeded,
boolean tokenJustRefreshed) throws IOException {
log.info("Sending request (token just refreshed: " + tokenJustRefreshed + "): "
+ describeRequest(req));
helper.authorize(req);
//log.info("req after authorizing: " + describeRequest(req));
HTTPResponse resp = fetch.fetch(req);
log.info("response: " + describeResponse(resp, false));
if (refreshNeeded.refreshNeeded(resp)) {
if (tokenJustRefreshed) {
throw new NeedNewOAuthTokenException("Token just refreshed, still no good: "
+ describeResponse(resp, true));
} else {
helper.refreshToken();
return fetch1(req, refreshNeeded, true);
}
} else {
return resp;
}
}
public HTTPResponse fetch(HTTPRequest request, TokenRefreshNeededDetector refreshNeeded)
throws IOException {
return fetch1(request, refreshNeeded, false);
}
public HTTPResponse fetch(HTTPRequest request) throws IOException {
return fetch(request, RESPONSE_CODE_401_DETECTOR);
}
// TODO(ohler): Move these static utility methods to some other utility class.
/** Gets the values of all headers with the name {@code headerName}. */
public static List<String> getHeaders(HTTPResponse resp, String headerName) {
ImmutableList.Builder<String> b = ImmutableList.builder();
for (HTTPHeader h : resp.getHeaders()) {
// HTTP header names are case-insensitive. App Engine downcases them when
// deployed but not when running locally.
if (headerName.equalsIgnoreCase(h.getName())) {
b.add(h.getValue());
}
}
return b.build();
}
/**
* Checks that exactly one header named {@code headerName} is present and
* returns its value.
*/
public static String getSingleHeader(HTTPResponse resp, String headerName) {
return Iterables.getOnlyElement(getHeaders(resp, headerName));
}
/** Returns the body of {@code resp}, assuming that its encoding is UTF-8. */
private static String getUtf8ResponseBodyUnchecked(HTTPResponse resp) {
byte[] rawResponseBody = resp.getContent();
if (rawResponseBody == null) {
return "";
} else {
return new String(rawResponseBody, Charsets.UTF_8);
}
}
/**
* Checks that the Content-Type of {@code resp} is
* {@code expectedUtf8ContentType} (which is assumed to imply UTF-8 encoding)
* and returns the body as a String.
*/
public static String getUtf8ResponseBody(HTTPResponse resp, String expectedUtf8ContentType)
throws IOException {
String contentType = getSingleHeader(resp, "Content-Type");
if (!expectedUtf8ContentType.equals(contentType)) {
throw new IOException("Unexpected Content-Type: " + contentType
+ " (wanted " + expectedUtf8ContentType + "); body as UTF-8: "
+ getUtf8ResponseBodyUnchecked(resp));
}
return getUtf8ResponseBodyUnchecked(resp);
}
}
| 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.server.auth;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.walkaround.wave.server.auth.ServletAuthHelper.UserServiceAccountLookup;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Filter that initializes {@link UserContext} from App Engine's
* {@link UserService}. Leaves the OAuth credentials in {@link UserContext} null if no
* OAuth token is stored for the user.
*
* @author ohler@google.com (Christian Ohler)
*/
@Singleton
public class InteractiveAuthFilter implements Filter {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(InteractiveAuthFilter.class.getName());
private final Provider<UserServiceAccountLookup> accountLookup;
private final Provider<ServletAuthHelper> helper;
private final Provider<User> user;
@Inject
public InteractiveAuthFilter(Provider<UserServiceAccountLookup> accountLookup,
Provider<ServletAuthHelper> helper,
Provider<User> user) {
this.accountLookup = accountLookup;
this.helper = helper;
this.user = user;
}
@Override
public void init(FilterConfig config) {}
@Override
public void destroy() {}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
final HttpServletRequest req = (HttpServletRequest) request;
final HttpServletResponse resp = (HttpServletResponse) response;
helper.get().filter(req, resp, filterChain, accountLookup.get(),
new ServletAuthHelper.NeedNewOAuthTokenHandler() {
@Override public void sendNeedTokenResponse() throws IOException {
helper.get().redirectToOAuthPage(req, resp, user.get().getEmail());
}
});
}
}
| 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.server.auth;
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.google.walkaround.util.server.auth.InvalidSecurityTokenException;
import com.google.walkaround.util.server.auth.SecurityTokenHelper;
import com.google.walkaround.util.server.servlet.BadRequestException;
import com.google.walkaround.wave.server.Flag;
import com.google.walkaround.wave.server.FlagName;
import java.util.logging.Logger;
/**
* Utility for creating and verifying XSRF tokens.
*
* @author ohler@google.com (Christian Ohler)
* @author danilatos@google.com (Daniel Danilatos)
*/
public class XsrfHelper {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(XsrfHelper.class.getName());
public static class XsrfTokenExpiredException extends Exception {
private static final long serialVersionUID = 467064784131563198L;
public XsrfTokenExpiredException() {
}
public XsrfTokenExpiredException(String message) {
super(message);
}
public XsrfTokenExpiredException(Throwable cause) {
super(cause);
}
public XsrfTokenExpiredException(String message, Throwable cause) {
super(message, cause);
}
}
private final SecurityTokenHelper helper;
private final long expiryMs;
private final StableUserId userId;
@Inject
public XsrfHelper(SecurityTokenHelper helper,
@Flag(FlagName.XSRF_TOKEN_EXPIRY_SECONDS) int expirySeconds,
StableUserId userId) {
Preconditions.checkArgument(!userId.getId().contains(" "),
"userId contains spaces: %s", userId);
this.helper = helper;
this.expiryMs = expirySeconds * 1000;
this.userId = userId;
}
private String makeHiddenPart(String action) {
return userId.getId() + " " + action;
}
public String createToken(String action) {
long timestamp = System.currentTimeMillis();
return helper.createToken(makeHiddenPart(action), "" + timestamp);
}
/**
* Verifies the token matches the current user and action and has not expired.
*/
public void verify(String action, String token)
throws XsrfTokenExpiredException, InvalidSecurityTokenException {
String visiblePart = helper.verifyAndGetVisiblePart(makeHiddenPart(action), token);
long tokenTime;
try {
tokenTime = Long.parseLong(visiblePart);
} catch (NumberFormatException e) {
throw new BadRequestException(e);
}
if (tokenTime + expiryMs < System.currentTimeMillis()) {
throw new XsrfTokenExpiredException("Token expired: " + action + ", " + userId
+ ", " + token);
}
}
}
| 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.server.auth;
/**
* Thrown when a new OAuth token is needed, either because the current token has
* been revoked, or because we have no token in the first place.
*
* @author ohler@google.com (Christian Ohler)
*/
public class NeedNewOAuthTokenException extends RuntimeException {
private static final long serialVersionUID = 162274534253085532L;
public NeedNewOAuthTokenException() {
}
public NeedNewOAuthTokenException(String message) {
super(message);
}
public NeedNewOAuthTokenException(Throwable cause) {
super(cause);
}
public NeedNewOAuthTokenException(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.wave.server.auth;
import com.google.inject.Inject;
import com.google.walkaround.util.server.RetryHelper.PermanentFailure;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Deletes the current user's OAuth token. This is useful to make walkaround
* forget a token to test the OAuth flow.
*
* @author ohler@google.com (Christian Ohler)
*/
public class DeleteOAuthTokenHandler extends AbstractHandler {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(DeleteOAuthTokenHandler.class.getName());
private final AccountStore accountStore;
private final StableUserId userId;
@Inject public DeleteOAuthTokenHandler(AccountStore accountStore,
StableUserId userId) {
this.accountStore = accountStore;
this.userId = userId;
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
try {
accountStore.delete(userId);
} catch (PermanentFailure e) {
throw new IOException("Failed to delete token for " + userId);
}
resp.sendRedirect("/");
}
}
| 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.server.auth;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.common.net.UriEscapers;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.walkaround.util.server.RetryHelper.PermanentFailure;
import org.waveprotocol.wave.model.wave.ParticipantId;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Utility methods for authentication filters.
*
* @author ohler@google.com (Christian Ohler)
*/
public class ServletAuthHelper {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(ServletAuthHelper.class.getName());
private final AccountStore accountStore;
private final UserContext userContext;
// Provider so that this helper can be instantiated for task queue handlers
// (where we have no User); serve() doesn't need the User as long as an
// AccountStore.Record is present. TODO(ohler): This is convoluted, find a
// better factoring. Should probably replace AccountLookup with a method to
// provide StableUserId and e-mail, and do the account store lookup in this
// helper.
private final Provider<User> user;
@Inject ServletAuthHelper(AccountStore accountStore,
UserContext userContext,
Provider<User> user) {
this.accountStore = accountStore;
this.userContext = userContext;
this.user = user;
}
private static String queryEncode(String s) {
return UriEscapers.uriQueryStringEscaper(false).escape(s);
}
public void redirectToOAuthPage(HttpServletRequest req, HttpServletResponse resp,
String email) throws IOException {
String originalRequest = req.getRequestURI()
+ (req.getQueryString() == null ? "" : "?" + req.getQueryString());
String targetUrl = "/enable?originalRequest=" + queryEncode(originalRequest);
log.info("Redirecting to OAuth page: " + targetUrl);
resp.sendRedirect(targetUrl);
}
private void populateContext(AccountStore.Record record) {
log.info("Populating " + userContext + " from record " + record);
userContext.setUserId(record.getUserId());
userContext.setParticipantId(record.getParticipantId());
userContext.setOAuthCredentials(record.getOAuthCredentials());
log.info("User context is now " + userContext);
}
private void clearOAuthTokenFromContext() {
log.info("Clearing OAuth token from " + userContext);
userContext.setOAuthCredentials(null);
log.info("User context is now " + userContext);
}
private void writeAccountRecord(AccountStore.Record record) throws IOException {
try {
accountStore.put(record);
} catch (PermanentFailure e) {
throw new IOException("Failed to write account record: " + record, e);
}
}
/**
* Extracts an account record from {@code userContext} and writes it to the
* account store unless it matches {@code storedRecord}.
*/
private void writeBackContextMaybe(@Nullable AccountStore.Record storedRecord)
throws IOException {
AccountStore.Record newRecord =
new AccountStore.Record(userContext.getUserId(), userContext.getParticipantId(),
userContext.hasOAuthCredentials() ? userContext.getOAuthCredentials() : null);
if (!newRecord.equals(storedRecord)) {
log.info("User context dirty, writing back:\nold=" + storedRecord
+ "\nnew=" + newRecord);
writeAccountRecord(newRecord);
} else {
log.info("User context unchanged, not writing back");
}
}
/** Extracts user id from the request and looks up account information. */
public interface AccountLookup {
/**
* Extracts the user id from the request and reads and returns the
* corresponding account store record.
*
* A null return value indicates that a new account store record should be
* created based on App Engine's {@link User} object.
*/
@Nullable AccountStore.Record getAccount() throws PermanentFailure, IOException;
}
/** Tells the client that a new OAuth token is needed. */
public interface NeedNewOAuthTokenHandler {
/** Sends a response that indicates that a new token is needed. */
void sendNeedTokenResponse() throws IOException;
}
/** Implements {@link AccountLookup} with App Engine's {@link UserService}. */
public static class UserServiceAccountLookup implements AccountLookup {
private final AccountStore accountStore;
private final User user;
@Inject public UserServiceAccountLookup(AccountStore accountStore, User user) {
this.accountStore = accountStore;
this.user = user;
}
@Override @Nullable public AccountStore.Record getAccount()
throws PermanentFailure, IOException {
return accountStore.get(new StableUserId(user.getUserId()));
}
}
/**
* Body for {@link #serve}.
*/
public interface ServletBody {
public void run() throws ServletException, IOException;
}
/**
* Invokes {@code body} with {@link UserContext} populated from
* {@code lookup.getAccount()}.
*
* Writes a new {@link AccountStore.Record} from {@code UserContext} and/or
* calls {@link NeedNewOAuthTokenHandler#sendNeedTokenResponse} as needed.
*/
public void serve(ServletBody body, AccountLookup lookup, NeedNewOAuthTokenHandler handler)
throws IOException, ServletException {
@Nullable AccountStore.Record record = null;
try {
try {
record = lookup.getAccount();
} catch (PermanentFailure e) {
throw new IOException("PermanentFailure getting account information", e);
}
if (record == null) {
userContext.setUserId(new StableUserId(user.get().getUserId()));
userContext.setParticipantId(ParticipantId.ofUnsafe(user.get().getEmail()));
} else {
populateContext(record);
}
body.run();
writeBackContextMaybe(record);
} catch (NeedNewOAuthTokenException e) {
// We don't log the stack trace since the situation is expected most of
// the time, and we don't want to draw attention to it in the logs (like a
// stack trace would).
log.info("Need new token: " + e);
if (record != null) {
// Delete the token so that the next page load will prompt to re-enable.
// TODO(ohler): Change the client to be able to prompt for a new token
// from within /wave.
writeAccountRecord(
new AccountStore.Record(userContext.getUserId(), userContext.getParticipantId(), null));
}
handler.sendNeedTokenResponse();
return;
}
}
/**
* Like {@link #serve}, but invokes {@code filterChain}.
*/
public void filter(final ServletRequest req, final ServletResponse resp,
final FilterChain filterChain, AccountLookup lookup, NeedNewOAuthTokenHandler handler)
throws IOException, ServletException {
serve(new ServletBody() {
@Override public void run() throws IOException, ServletException {
filterChain.doFilter(req, resp);
}
}, lookup, handler);
}
}
| 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.server.auth;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import java.io.Serializable;
/**
* OAuth2 credentials for a given user.
*
* @author ohler@google.com (Christian Ohler)
*/
public class OAuthCredentials implements Serializable {
private static final long serialVersionUID = 394301039547092998L;
private final String refreshToken;
private final String accessToken;
public OAuthCredentials(String refreshToken, String accessToken) {
Preconditions.checkNotNull(refreshToken, "Null refreshToken");
Preconditions.checkNotNull(accessToken, "Null accessToken");
this.refreshToken = refreshToken;
this.accessToken = accessToken;
}
public String getRefreshToken() {
return refreshToken;
}
public String getAccessToken() {
return accessToken;
}
@Override public String toString() {
return "OAuthCredentials(" + refreshToken + ", " + accessToken + ")";
}
@Override public final boolean equals(Object o) {
if (o == this) { return true; }
if (!(o instanceof OAuthCredentials)) { return false; }
OAuthCredentials other = (OAuthCredentials) o;
return Objects.equal(refreshToken, other.refreshToken)
&& Objects.equal(accessToken, other.accessToken);
}
@Override public final int hashCode() {
return Objects.hashCode(refreshToken, accessToken);
}
}
| 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.server;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.util.server.appengine.AbstractDirectory;
import com.google.walkaround.util.server.appengine.CheckedDatastore;
import com.google.walkaround.util.server.appengine.DatastoreUtil.InvalidPropertyException;
import com.google.walkaround.util.server.appengine.MemcacheTable;
import java.io.IOException;
import java.io.Serializable;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Interface to the wavelet directory in the datastore.
*
* Directory entries are also cached in memcache. Wavelet ids that were looked
* up but didn't exist are also cached to avoid paying a high cost if someone
* repeatedly requests the same bogus wavelet id. The cache does not help with
* rapid requests of different bogus (or valid) wavelet ids, but at least those
* will be distributed across entity groups.
*
* @author ohler@google.com (Christian Ohler)
*/
// Like WaveletMapping, this class is rather degenerate right now: The directory
// is nothing but a set of SlobIds, and all the memcache does is avoid datastore
// lookups for wavelets that we know don't exist.
public class WaveletDirectory {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(WaveletDirectory.class.getName());
/**
* Thrown when an attempt is made to register a wavelet that is already known in
* the wavelet directory.
*
* @author ohler@google.com (Christian Ohler)
*/
public class ObjectIdAlreadyKnown extends Exception {
private static final long serialVersionUID = 800996175494608917L;
private final WaveletMapping existingMapping;
public ObjectIdAlreadyKnown(WaveletMapping existingMapping) {
this(existingMapping, null, null);
}
public ObjectIdAlreadyKnown(WaveletMapping existingMapping, String message) {
this(existingMapping, message, null);
}
public ObjectIdAlreadyKnown(WaveletMapping existingMapping, Throwable cause) {
this(existingMapping, null, cause);
}
public ObjectIdAlreadyKnown(WaveletMapping existingMapping,
String message, Throwable cause) {
super(message, cause);
Preconditions.checkNotNull(existingMapping, "Null existingMapping");
this.existingMapping = existingMapping;
}
public WaveletMapping getExistingMapping() {
return existingMapping;
}
}
@VisibleForTesting
static class CacheEntry implements Serializable {
private static final long serialVersionUID = 310319261711079447L;
@Nullable private final WaveletMapping cached;
public CacheEntry(@Nullable WaveletMapping cached) {
this.cached = cached;
}
/** Null if wavelet does not exist. */
@Nullable public WaveletMapping getCached() {
return cached;
}
@Override public String toString() {
return "CacheEntry(" + cached + ")";
}
}
@VisibleForTesting
static class Directory extends AbstractDirectory<WaveletMapping, SlobId> {
Directory(CheckedDatastore datastore) {
super(datastore, "WaveletDirectoryEntry");
}
@Override protected String serializeId(SlobId id) {
return id.getId();
}
@Override protected SlobId getId(WaveletMapping mapping) {
return mapping.getObjectId();
}
@Override protected void populateEntity(WaveletMapping mapping, Entity out) {
}
@Override protected WaveletMapping parse(Entity e) throws InvalidPropertyException {
return new WaveletMapping(new SlobId(e.getKey().getName()));
}
}
private static final String MEMCACHE_TAG = "W";
@VisibleForTesting
final Directory directory;
@VisibleForTesting
final MemcacheTable<SlobId, CacheEntry> cache;
@Inject
public WaveletDirectory(CheckedDatastore datastore, MemcacheTable.Factory memcacheFactory) {
this.directory = new Directory(datastore);
this.cache = memcacheFactory.create(MEMCACHE_TAG);
}
/**
* Returns null if object id is not known. (This doesn't mean the id is not
* assigned; it may be assigned in the object store, which is authoritative,
* but not in the directory.)
* @throws IOException
*/
@Nullable public WaveletMapping lookup(SlobId objectId) throws IOException {
CacheEntry cached = cache.get(objectId);
if (cached != null) {
return cached.getCached();
}
WaveletMapping result = directory.getWithoutTx(objectId);
if (result != null) {
cache.put(objectId, new CacheEntry(result));
return result;
} else {
// We have to use ADD_ONLY_IF_NOT_PRESENT since there may be a concurrent
// register() also trying to set the value, and that has to take priority.
cache.put(objectId, new CacheEntry(null), null,
MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT);
return null;
}
}
public void register(WaveletMapping newMapping) throws IOException, ObjectIdAlreadyKnown {
Preconditions.checkNotNull(newMapping, "Null newMapping");
// We do a cache lookup here to detect inconsistencies (and perhaps to catch
// bugs that create the same wavelet more than once cheaper than the
// datastore could do it). It's not strictly necessary, but the datastore
// access that follows is much more expensive anyway, so we don't mind the
// extra cache lookup.
CacheEntry cached = cache.get(newMapping.getObjectId());
if (cached != null && cached.getCached() != null) {
throw new ObjectIdAlreadyKnown(cached.getCached(),
"Attempt to register " + newMapping
+ ", but object already exists (cached = " + cached + ")");
}
log.info("About to register " + newMapping);
WaveletMapping existingMapping = directory.getOrAdd(newMapping);
log.info("Existing mapping: " + existingMapping);
if (existingMapping != null) {
throw new ObjectIdAlreadyKnown(existingMapping,
"Attempt to register " + newMapping + ", but object already exists: " + existingMapping
+ " (cached = " + cached + ")");
}
cache.put(newMapping.getObjectId(), new CacheEntry(newMapping));
}
}
| 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.server.util;
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.Preconditions;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* A servlet that proxies HTTP requests synchronously to another URL.
*
* @author hearnden@google.com (David Hearnden)
*/
public final class ProxyHandler extends AbstractHandler {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(ProxyHandler.class.getName());
/** Part of incoming requests to rewrite. e.g., "/gadgets". */
private final String sourceUriPrefix;
/** Value on which to rebase incoming URLs. e.g., "http://gmodules.com". */
private final String targetUriPrefix;
/** Fetch service. Used in favor of HttpURLConnection for greater control. */
private final URLFetchService fetch;
/**
* Creates a proxy servlet.
*
* @param sourceUriPrefix prefix of incoming requests to rewrite
* @param targetUriPrefix value to replace the source prefix
* @param fetch
*/
public ProxyHandler(String sourceUriPrefix, String targetUriPrefix, URLFetchService fetch) {
// To prevent silly things like fowarding to ../
Preconditions.checkArgument(!targetUriPrefix.contains(".."));
this.sourceUriPrefix = sourceUriPrefix;
this.targetUriPrefix = targetUriPrefix;
this.fetch = fetch;
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
proxy(req, resp);
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
proxy(req, resp);
}
private void proxy(HttpServletRequest req, HttpServletResponse resp) throws IOException {
if (!req.getRequestURI().startsWith(sourceUriPrefix)) {
log.info("Not proxying request to " + req.getRequestURI()
+ ", does not start with " + sourceUriPrefix);
return;
}
String sourceUri = req.getRequestURI();
String query = req.getQueryString() != null ? req.getQueryString() : "";
String targetUri = targetUriPrefix + sourceUri.substring(sourceUriPrefix.length()) + query;
log.info("Forwarding request: " + sourceUri + query + " to " + targetUri);
HTTPMethod fetchMethod = HTTPMethod.valueOf(req.getMethod());
HTTPRequest fetchRequest = new HTTPRequest(new URL(targetUri), fetchMethod);
fetchRequest.setPayload(copy(req.getInputStream(), new ByteArrayOutputStream()).toByteArray());
HTTPResponse fetchResponse = fetch.fetch(fetchRequest);
copyResponse(fetchResponse, resp);
}
public static void copyResponse(HTTPResponse from, HttpServletResponse to) throws IOException {
to.setStatus(from.getResponseCode());
copy(new ByteArrayInputStream(from.getContent()), to.getOutputStream());
}
/**
* Transfers one stream to another. Raw streams are used rather than
* string-based readers/writers in case the byte format of the streams is not
* UTF-16.
*
* @return output, for convenience.
*/
private static <T extends OutputStream> T copy(InputStream input, T output) throws IOException {
byte[] buffer = new byte[8192];
int read;
while ((read = input.read(buffer, 0, buffer.length)) > 0) {
output.write(buffer, 0, read);
}
output.flush();
return output;
}
}
| 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.server;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import com.google.walkaround.proto.WalkaroundWaveletSnapshot;
import com.google.walkaround.proto.WaveletDiffSnapshot;
import com.google.walkaround.slob.server.AccessDeniedException;
import com.google.walkaround.slob.server.SlobNotFoundException;
import com.google.walkaround.slob.server.SlobStore;
import com.google.walkaround.slob.server.SlobStore.ConnectResult;
import com.google.walkaround.slob.server.SlobStore.HistoryResult;
import com.google.walkaround.slob.shared.ChangeData;
import com.google.walkaround.slob.shared.ClientId;
import com.google.walkaround.slob.shared.MessageException;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.util.shared.Assert;
import com.google.walkaround.wave.server.conv.ConvStore;
import com.google.walkaround.wave.server.model.ServerMessageSerializer;
import com.google.walkaround.wave.server.udw.UdwStore;
import com.google.walkaround.wave.shared.IdHack;
import com.google.walkaround.wave.shared.WaveSerializer;
import org.waveprotocol.wave.model.document.operation.DocInitialization;
import org.waveprotocol.wave.model.document.operation.automaton.DocumentSchema;
import org.waveprotocol.wave.model.id.WaveletId;
import org.waveprotocol.wave.model.id.WaveletName;
import org.waveprotocol.wave.model.supplement.PrimitiveSupplement;
import org.waveprotocol.wave.model.supplement.WaveletBasedSupplement;
import org.waveprotocol.wave.model.util.CollectionUtils;
import org.waveprotocol.wave.model.util.Pair;
import org.waveprotocol.wave.model.util.StringMap;
import org.waveprotocol.wave.model.wave.data.DocumentFactory;
import org.waveprotocol.wave.model.wave.data.impl.ObservablePluggableMutableDocument;
import org.waveprotocol.wave.model.wave.data.impl.WaveletDataImpl;
import org.waveprotocol.wave.model.wave.opbased.OpBasedWavelet;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Handles loading waves.
*
* @author danilatos@google.com (Daniel Danilatos)
* @author ohler@google.com (Christian Ohler)
*/
public class WaveLoader {
public static class LoadedUdw {
private final SlobId objectId;
private final ConnectResult connectResult;
private final WalkaroundWaveletSnapshot snapshot;
public LoadedUdw(SlobId objectId,
ConnectResult connectResult,
WalkaroundWaveletSnapshot snapshot) {
Preconditions.checkNotNull(objectId, "Null objectId");
Preconditions.checkNotNull(connectResult, "Null connectResult");
Preconditions.checkNotNull(snapshot, "Null snapshot");
this.objectId = objectId;
this.connectResult = connectResult;
this.snapshot = snapshot;
}
public SlobId getObjectId() {
return objectId;
}
public ConnectResult getConnectResult() {
return connectResult;
}
public WalkaroundWaveletSnapshot getSnapshot() {
return snapshot;
}
@Override public String toString() {
return "LoadedUdw(" + objectId + ", " + connectResult + ")";
}
}
public static class LoadedWave {
private final SlobId convObjectId;
@Nullable private final ConnectResult convConnectResult;
private final WaveletDiffSnapshot convSnapshotWithDiffs;
@Nullable private final LoadedUdw udw;
public LoadedWave(SlobId convObjectId,
@Nullable ConnectResult convConnectResult,
WaveletDiffSnapshot convSnapshotWithDiffs,
@Nullable LoadedUdw udw) {
this.convObjectId = checkNotNull(convObjectId, "Null convObjectId");
this.convConnectResult = convConnectResult;
this.convSnapshotWithDiffs =
checkNotNull(convSnapshotWithDiffs, "Null convSnapshotWithDiffs");
this.udw = udw;
}
public SlobId getConvObjectId() {
return convObjectId;
}
@Nullable public ConnectResult getConvConnectResult() {
return convConnectResult;
}
public WaveletDiffSnapshot getConvSnapshotWithDiffs() {
return convSnapshotWithDiffs;
}
@Nullable public LoadedUdw getUdw() {
return udw;
}
@Override public String toString() {
return getClass().getSimpleName() + "("
+ convObjectId + ", "
+ convConnectResult + ", "
+ convSnapshotWithDiffs + ", "
+ udw
+ ")";
}
}
private static final Logger log = Logger.getLogger(WaveLoader.class.getName());
private final WaveletCreator waveletCreator;
private final SlobStore convStore;
private final SlobStore udwStore;
private final boolean enableUdw;
private final boolean enableDiffOnOpen;
private final WaveSerializer serializer;
@Inject
public WaveLoader(WaveletCreator waveletCreator,
@Flag(FlagName.ENABLE_UDW) boolean enableUdw,
@Flag(FlagName.ENABLE_DIFF_ON_OPEN) boolean enableDiffOnOpen,
@ConvStore SlobStore convStore,
@UdwStore SlobStore udwStore) {
this.waveletCreator = waveletCreator;
this.convStore = convStore;
this.udwStore = udwStore;
this.enableUdw = enableUdw;
this.enableDiffOnOpen = enableDiffOnOpen;
serializer = new WaveSerializer(new ServerMessageSerializer(),
new DocumentFactory<ObservablePluggableMutableDocument>() {
@Override public ObservablePluggableMutableDocument create(
WaveletId waveletId, String docId, DocInitialization content) {
return new ObservablePluggableMutableDocument(
DocumentSchema.NO_SCHEMA_CONSTRAINTS, content);
}
});
}
public LoadedWave loadStaticAtVersion(SlobId convObjectId, @Nullable Long version)
throws IOException, AccessDeniedException, SlobNotFoundException {
Preconditions.checkNotNull(convObjectId, "Null convObjectId");
String rawConvSnapshot = convStore.loadAtVersion(convObjectId, version);
WaveletName convWaveletName = IdHack.convWaveletNameFromConvObjectId(convObjectId);
WaveletDataImpl convWavelet = deserializeWavelet(convWaveletName, rawConvSnapshot);
// TODO(ohler): Determine if it's better UX if we load the UDW here as well.
return waveWithoutUdw(convObjectId, null, convWavelet);
}
public LoadedWave load(SlobId convObjectId, ClientId clientId)
throws IOException, AccessDeniedException, SlobNotFoundException {
Preconditions.checkNotNull(convObjectId, "Null convObjectId");
Preconditions.checkNotNull(clientId, "Null clientId");
Pair<ConnectResult, String> convPair = convStore.connect(convObjectId, clientId);
ConnectResult convResult = convPair.getFirst();
String rawConvSnapshot = convPair.getSecond();
log(convObjectId, convResult);
WaveletName convWaveletName = IdHack.convWaveletNameFromConvObjectId(convObjectId);
// The most recent version of wavelet to get list of documents from.
WaveletDataImpl convWavelet = deserializeWavelet(convWaveletName, rawConvSnapshot);
long convVersion = convResult.getVersion();
Assert.check(convVersion == convWavelet.getVersion(),
"ConnectResult revision %s does not match wavelet version %s",
convVersion, convWavelet.getVersion());
if (!enableUdw) {
return waveWithoutUdw(convObjectId, convResult, convWavelet);
} else {
// Now we go and load some of the history in order to render diffs.
// For fully read or unread blips, we don't need to load any history.
// So the approach here is to find all the blips that are partially
// read, and get the smallest version.
// TODO(ohler): This should be getOrCreateAndConnect(), so that we can avoid
// reconstructing the state of the wavelet that we just created. But
// snapshot caching would help with this as well, so we should probably do
// that first.
SlobId udwId = waveletCreator.getOrCreateUdw(convObjectId);
Pair<ConnectResult, String> udwPair;
try {
udwPair = udwStore.connect(udwId, clientId);
} catch (SlobNotFoundException e) {
throw new RuntimeException("UDW disappeared right after getOrCreateUdw(): " + udwId);
}
ConnectResult udwResult = udwPair.getFirst();
WaveletName udwWaveletName = IdHack.udwWaveletNameFromConvObjectIdAndUdwObjectId(
convObjectId, udwId);
WaveletDataImpl udw = deserializeWavelet(udwWaveletName, udwPair.getSecond());
WalkaroundWaveletSnapshot udwSnapshot = serializer.createWaveletMessage(udw);
LoadedUdw loadedUdw = new LoadedUdw(udwId, udwResult, udwSnapshot);
if (!enableDiffOnOpen) {
return waveWithoutDiffs(convObjectId, convResult, convWavelet, loadedUdw);
}
StringMap<Long> lastReadVersions = getLastReadVersions(udw, convWavelet);
// The intermediate revision we'll load our wave in, as a simple optimization
// that avoids loading most of the history in many use cases. We can try to
// be smarter about this eventually.
long intermediateVersion = getMinReadVersion(convWavelet, lastReadVersions);
if (intermediateVersion <= 0 || intermediateVersion > convVersion) {
throw new AssertionError("Invalid intermediateVersion " + intermediateVersion
+ ", conv version = " + convVersion);
}
String intermediateSnapshot;
if (intermediateVersion == convVersion) {
intermediateSnapshot = rawConvSnapshot;
} else {
try {
intermediateSnapshot = convStore.loadAtVersion(convObjectId, intermediateVersion);
} catch (SlobNotFoundException e) {
throw new RuntimeException(
"Conv object disappeared when trying to load intermediate version: " + convObjectId);
}
}
WaveletDataImpl intermediateWavelet = deserializeWavelet(convWaveletName,
intermediateSnapshot);
Assert.check(intermediateWavelet.getVersion() == intermediateVersion);
// We have to stop getting the history at conv version, because we're not
// computing the metadata again for any concurrent ops that got added
// since we loaded the convResult - so we don't want them getting added
// into our diff snapshot. We can let the client catch up instead.
HistoryResult history;
try {
history = convStore.loadHistory(convObjectId, intermediateVersion, convVersion);
} catch (SlobNotFoundException e) {
throw new RuntimeException(
"Conv object disappeared when trying to load history: " + convObjectId);
}
// Graceful degrade to no diff-on-open if there was too much data.
// TODO(danilatos): Potentially try to load more history if there's time,
// or, memcache the current progress so a refresh would have a better
// chance... or implement composition trees... or some other improvement.
if (history.hasMore()) {
return waveWithoutDiffs(convObjectId, convResult, convWavelet, loadedUdw);
}
List<String> mutations = mutations(history.getData());
WaveletDiffSnapshot convSnapshot = serializer.createWaveletDiffMessage(
intermediateWavelet, convWavelet, lastReadVersions, mutations);
return new LoadedWave(convObjectId, convResult, convSnapshot, loadedUdw);
}
}
private LoadedWave waveWithoutUdw(SlobId convObjectId,
ConnectResult convResult, WaveletDataImpl convWavelet) {
return waveWithoutDiffs(convObjectId, convResult, convWavelet, null);
}
private LoadedWave waveWithoutDiffs(SlobId convObjectId,
ConnectResult convResult, WaveletDataImpl convWavelet, @Nullable LoadedUdw udw) {
WaveletDiffSnapshot convSnapshot = serializer.createWaveletDiffMessage(convWavelet, convWavelet,
CollectionUtils.<Long>createStringMap(), Collections.<String>emptyList());
return new LoadedWave(convObjectId, convResult, convSnapshot, udw);
}
/**
* Creates a mapping of documents to their last read versions in wavelet
*/
private StringMap<Long> getLastReadVersions(WaveletDataImpl udw, WaveletDataImpl conv) {
StringMap<Long> lastReadVersions = CollectionUtils.createStringMap();
WaveletBasedSupplement supplement = WaveletBasedSupplement.create(
OpBasedWavelet.createReadOnly(udw));
for (String documentId : conv.getDocumentIds()) {
long lastReadBlipVersion = supplement.getLastReadBlipVersion(conv.getWaveletId(), documentId);
if (lastReadBlipVersion == PrimitiveSupplement.NO_VERSION) {
continue;
}
Assert.check(lastReadBlipVersion >= 0);
lastReadVersions.put(documentId, lastReadBlipVersion);
}
return lastReadVersions;
}
List<String> mutations(List<ChangeData<String>> data) {
List<String> mutations = Lists.newArrayList();
for (ChangeData<String> c : data) {
mutations.add(c.getPayload());
}
return mutations;
}
private void log(SlobId objectId, ConnectResult result) {
log.info("enableUdw: " + enableUdw + ", load(" + objectId + "): " + result);
}
/**
* Calculates the minimum read version of all documents that have been
* partially read, with a base case of the current wavelet version
*
* I.e. if there are no partially read documents, i.e. each document is either
* entirely read or entirely unread, then the wavelet version is returned.
*
* The domain of document ids from the current state of the wavelet is used,
* rather than the domain of lastReadVersions, in order to filter out read
* documents that no longer exist.
*/
private long getMinReadVersion(
WaveletDataImpl wavelet, StringMap<Long> lastReadVersions) {
long minVersion = wavelet.getVersion();
for (String documentId : wavelet.getDocumentIds()) {
long documentReadVersion = lastReadVersions.get(documentId, 0L);
long documentModifiedVersion = wavelet.getDocument(documentId).getLastModifiedVersion();
if (documentReadVersion >= documentModifiedVersion) {
continue;
}
if (documentReadVersion == 0) {
continue;
}
if (documentReadVersion < minVersion) {
minVersion = documentReadVersion;
}
}
return minVersion;
}
private WaveletDataImpl deserializeWavelet(WaveletName waveletName, String snapshot) {
try {
return serializer.deserializeWavelet(waveletName, snapshot);
} catch (MessageException e) {
throw new RuntimeException("Invalid snapshot for " + waveletName, 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.wave.server;
/**
* Type of object store.
*
* @author ohler@google.com (Christian Ohler)
*/
public enum StoreType {
CONV, UDW;
public String serialize() {
return toString();
}
public static StoreType parse(String input) {
return valueOf(input);
}
}
| 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.server.googleimport;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Multimap;
import com.google.common.net.UriEscapers;
import com.google.gxp.base.GxpContext;
import com.google.gxp.html.HtmlClosure;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.walkaround.proto.ImportSettings;
import com.google.walkaround.proto.ImportSettings.ImportSharingMode;
import com.google.walkaround.proto.ImportTaskPayload;
import com.google.walkaround.proto.ImportWaveletTask;
import com.google.walkaround.proto.gson.ImportSettingsGsonImpl;
import com.google.walkaround.proto.gson.ImportTaskPayloadGsonImpl;
import com.google.walkaround.proto.gson.ImportWaveletTaskGsonImpl;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.util.server.HtmlEscaper;
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.auth.InvalidSecurityTokenException;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import com.google.walkaround.util.server.servlet.BadRequestException;
import com.google.walkaround.util.shared.Assert;
import com.google.walkaround.wave.server.Flag;
import com.google.walkaround.wave.server.FlagName;
import com.google.walkaround.wave.server.auth.NeedNewOAuthTokenException;
import com.google.walkaround.wave.server.auth.StableUserId;
import com.google.walkaround.wave.server.auth.UserContext;
import com.google.walkaround.wave.server.auth.XsrfHelper;
import com.google.walkaround.wave.server.auth.XsrfHelper.XsrfTokenExpiredException;
import com.google.walkaround.wave.server.gxp.ImportOverviewFragment;
import com.google.walkaround.wave.server.gxp.ImportWaveletDisplayRecord;
import com.google.walkaround.wave.server.gxp.SourceInstance;
import com.google.walkaround.wave.server.servlet.PageSkinWriter;
import org.joda.time.Instant;
import org.joda.time.LocalDate;
import org.waveprotocol.wave.model.id.WaveId;
import org.waveprotocol.wave.model.id.WaveletId;
import org.waveprotocol.wave.model.id.WaveletName;
import org.waveprotocol.wave.model.util.Pair;
import org.waveprotocol.wave.model.wave.ParticipantId;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Interactive entry point for import features.
*
* @author ohler@google.com (Christian Ohler)
*/
// For now, this shows a lot of detail, more than typical users would want.
// Once it works well, we should simplify it.
public class ImportOverviewHandler extends AbstractHandler {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(ImportOverviewHandler.class.getName());
private static final String XSRF_ACTION = "importaction";
@Inject ParticipantId participantId;
@Inject StableUserId userId;
@Inject XsrfHelper xsrfHelper;
@Inject SourceInstance.Factory sourceInstanceFactory;
@Inject TaskDispatcher taskDispatcher;
// Providers because the values are only needed in some branches of the code.
@Inject Provider<CheckedDatastore> datastore;
@Inject Provider<PerUserTable> perUserTable;
@Inject Provider<FindRemoteWavesProcessor> findProcessor;
@Inject PageSkinWriter pageSkinWriter;
@Inject UserContext userContext;
@Inject @Flag(FlagName.IMPORT_PRESERVE_HISTORY) boolean preserveHistory;
private String makeLocalWaveLink(SlobId convSlobId) {
return "/wave?id=" + UriEscapers.uriQueryStringEscaper(false).escape(convSlobId.getId());
}
private List<ImportWaveletDisplayRecord> getWaves(CheckedTransaction tx,
Multimap<Pair<SourceInstance, WaveletName>, ImportSharingMode> importsInProgress)
throws RetryableFailure, PermanentFailure {
ImmutableList.Builder<ImportWaveletDisplayRecord> out = ImmutableList.builder();
List<RemoteConvWavelet> wavelets = perUserTable.get().getAllWavelets(tx, userId);
for (RemoteConvWavelet wavelet : wavelets) {
WaveletName waveletName = WaveletName.of(
WaveId.deserialise(wavelet.getDigest().getWaveId()),
wavelet.getWaveletId());
out.add(
new ImportWaveletDisplayRecord(
wavelet.getSourceInstance(),
waveletName,
wavelet.getSourceInstance().getWaveLink(waveletName.waveId),
// Let's assume that participant 0 is the creator even if that's not always true.
// Participant lists can be empty.
wavelet.getDigest().getParticipantSize() == 0
? "<unknown>"
: wavelet.getDigest().getParticipant(0),
wavelet.getDigest().getTitle(),
"" + new LocalDate(new Instant(wavelet.getDigest().getLastModifiedMillis())),
importsInProgress.containsEntry(Pair.of(wavelet.getSourceInstance(), waveletName),
ImportSharingMode.PRIVATE)
|| importsInProgress.containsEntry(Pair.of(wavelet.getSourceInstance(),
waveletName), ImportSharingMode.PRIVATE_UNLESS_PARTICIPANT),
wavelet.getPrivateLocalId() == null ? null : wavelet.getPrivateLocalId().getId(),
wavelet.getPrivateLocalId() == null ? null
: makeLocalWaveLink(wavelet.getPrivateLocalId()),
importsInProgress.containsEntry(Pair.of(wavelet.getSourceInstance(), waveletName),
ImportSharingMode.SHARED)
|| importsInProgress.containsEntry(Pair.of(wavelet.getSourceInstance(),
waveletName), ImportSharingMode.PRIVATE_UNLESS_PARTICIPANT),
wavelet.getSharedLocalId() == null ? null : wavelet.getSharedLocalId().getId(),
wavelet.getSharedLocalId() == null ? null
: makeLocalWaveLink(wavelet.getSharedLocalId())));
}
return out.build();
}
private String getInstanceSelectionHtml() {
StringBuilder out = new StringBuilder();
boolean first = true;
for (SourceInstance instance : sourceInstanceFactory.getInstances()) {
String instanceId = instance.serialize();
Assert.check(instanceId.matches("[a-zA-Z_.]+"),
"Bad characters in instance id: %s", instance);
out.append("<input type='radio'" + (first ? " checked='checked'" : "")
+ " name='instance' value='" + instanceId + "'/> "
+ HtmlEscaper.HTML_ESCAPER.escape(instance.getLongName())
+ "<br/>");
first = false;
}
return out.toString();
}
private List<String> describeTasks(List<ImportTask> tasks) {
ImmutableList.Builder<String> out = ImmutableList.builder();
for (ImportTask task : tasks) {
out.add(taskDispatcher.describeTask(task));
}
return out.build();
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
if (!userContext.hasOAuthCredentials()) {
throw new NeedNewOAuthTokenException("No OAuth credentials: " + userContext);
}
Pair<List<String>, List<ImportWaveletDisplayRecord>> pair;
try {
pair = new RetryHelper().run(
new RetryHelper.Body<Pair<List<String>, List<ImportWaveletDisplayRecord>>>() {
@Override public Pair<List<String>, List<ImportWaveletDisplayRecord>> run()
throws RetryableFailure, PermanentFailure {
CheckedTransaction tx = datastore.get().beginTransaction();
try {
List<ImportTask> tasksInProgress = perUserTable.get().getAllTasks(tx, userId);
return Pair.of(describeTasks(tasksInProgress),
getWaves(tx, taskDispatcher.waveletImportsInProgress(tasksInProgress)));
} finally {
tx.rollback();
}
}
});
} catch (PermanentFailure e) {
throw new IOException("PermanentFailure retrieving import records", e);
}
List<String> tasksInProgress = pair.getFirst();
List<ImportWaveletDisplayRecord> waveDisplayRecords = pair.getSecond();
final String instanceSelectionHtml = getInstanceSelectionHtml();
resp.setContentType("text/html");
resp.setCharacterEncoding("UTF-8");
pageSkinWriter.write("Walkaround Import", participantId.getAddress(),
ImportOverviewFragment.getGxpClosure(
participantId.getAddress(),
xsrfHelper.createToken(XSRF_ACTION),
new HtmlClosure() {
@Override public void write(Appendable out, GxpContext context) throws IOException {
out.append(instanceSelectionHtml);
}
},
tasksInProgress,
waveDisplayRecords));
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
if (!userContext.hasOAuthCredentials()) {
throw new NeedNewOAuthTokenException("POST with no OAuth credentials: " + userContext);
}
try {
xsrfHelper.verify(XSRF_ACTION, requireParameter(req, "token"));
} catch (XsrfTokenExpiredException e) {
throw new BadRequestException(e);
} catch (InvalidSecurityTokenException e) {
throw new BadRequestException(e);
}
String action = requireParameter(req, "action");
if ("findwaves".equals(action) || "findandimport".equals(action)) {
SourceInstance instance =
sourceInstanceFactory.parseUnchecked(requireParameter(req, "instance"));
// Rather than enqueueing just one interval 2008-01-01 to 2013-01-01, we
// split that interval into random parts. See the note on randomization
// in FindRemoteWavesProcessor.
log.info("Enqueueing find waves tasks");
@Nullable ImportSettings autoImportSettings;
if ("findwaves".equals(action)) {
autoImportSettings = null;
} else {
autoImportSettings = new ImportSettingsGsonImpl();
autoImportSettings.setSynthesizeHistory(!preserveHistory);
if ("private".equals(requireParameter(req, "sharingmode"))) {
autoImportSettings.setSharingMode(ImportSharingMode.PRIVATE);
} else if ("shared".equals(requireParameter(req, "sharingmode"))) {
autoImportSettings.setSharingMode(ImportSharingMode.SHARED);
} else if ("privateunlessparticipant".equals(requireParameter(req, "sharingmode"))) {
autoImportSettings.setSharingMode(ImportSharingMode.PRIVATE_UNLESS_PARTICIPANT);
} else {
throw new BadRequestException("Bad sharingmode");
}
}
enqueueTasks(findProcessor.get().makeRandomTasksForInterval(instance,
DaysSinceEpoch.fromYMD(2008, 1, 1),
DaysSinceEpoch.fromYMD(2013, 1, 1),
autoImportSettings));
} else if ("importwavelet".equals(action)) {
SourceInstance instance =
sourceInstanceFactory.parseUnchecked(requireParameter(req, "instance"));
WaveId waveId = WaveId.deserialise(requireParameter(req, "waveid"));
WaveletId waveletId = WaveletId.deserialise(requireParameter(req, "waveletid"));
ImportWaveletTask task = new ImportWaveletTaskGsonImpl();
task.setInstance(instance.serialize());
task.setWaveId(waveId.serialise());
task.setWaveletId(waveletId.serialise());
ImportSettings settings = new ImportSettingsGsonImpl();
if ("private".equals(requireParameter(req, "sharingmode"))) {
settings.setSharingMode(ImportSettings.ImportSharingMode.PRIVATE);
} else if ("shared".equals(requireParameter(req, "sharingmode"))) {
settings.setSharingMode(ImportSettings.ImportSharingMode.SHARED);
} else {
throw new BadRequestException("Unexpected import sharing mode");
}
settings.setSynthesizeHistory(!preserveHistory);
task.setSettings(settings);
@Nullable String existingSlobIdToIgnore = optionalParameter(req, "ignoreexisting", null);
if (existingSlobIdToIgnore != null) {
task.setExistingSlobIdToIgnore(existingSlobIdToIgnore);
}
final ImportTaskPayload payload = new ImportTaskPayloadGsonImpl();
payload.setImportWaveletTask(task);
log.info("Enqueueing import task for " + waveId
+ "; synthesizeHistory=" + task.getSettings().getSynthesizeHistory());
enqueueTasks(ImmutableList.of(payload));
} else if ("canceltasks".equals(action)) {
log.info("Cancelling all tasks for " + userId);
try {
new RetryHelper().run(new RetryHelper.VoidBody() {
@Override public void run() throws RetryableFailure, PermanentFailure {
CheckedTransaction tx = datastore.get().beginTransaction();
try {
if (perUserTable.get().deleteAllTasks(tx, userId)) {
tx.commit();
}
} finally {
tx.close();
}
}
});
} catch (PermanentFailure e) {
throw new IOException("Failed to delete tasks", e);
}
} else if ("forgetwaves".equals(action)) {
log.info("Forgetting all waves for " + userId);
try {
new RetryHelper().run(new RetryHelper.VoidBody() {
@Override public void run() throws RetryableFailure, PermanentFailure {
CheckedTransaction tx = datastore.get().beginTransaction();
try {
if (perUserTable.get().deleteAllWaves(tx, userId)) {
tx.commit();
}
} finally {
tx.close();
}
}
});
} catch (PermanentFailure e) {
throw new IOException("Failed to delete tasks", e);
}
} else {
throw new BadRequestException("Unknown action: " + action);
}
// TODO(ohler): Send 303, not 302. See
// http://en.wikipedia.org/wiki/Post/Redirect/Get .
resp.sendRedirect(req.getServletPath());
}
private void enqueueTasks(final List<ImportTaskPayload> payloads) throws IOException {
try {
new RetryHelper().run(new RetryHelper.VoidBody() {
@Override public void run() throws RetryableFailure, PermanentFailure {
CheckedTransaction tx = datastore.get().beginTransaction();
try {
for (ImportTaskPayload payload : payloads) {
perUserTable.get().addTask(tx, userId, payload);
}
tx.commit();
} finally {
tx.close();
}
}
});
} catch (PermanentFailure e) {
throw new IOException("Failed to enqueue import task", 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.wave.server.googleimport.conversion;
/**
* Thrown when data that we're trying to import is invalid.
*
* Any occurrences of this exception have to be considered bugs in the importer
* even if they are caused by googlewave.com giving us corrupt data, since
* googlewave.com is pretty much set in stone, and the importer has to work
* around all of its quirks.
*
* @author ohler@google.com (Christian Ohler)
*/
public class InvalidInputException extends RuntimeException {
private static final long serialVersionUID = 168128706679979507L;
public InvalidInputException() {
}
public InvalidInputException(String message) {
super(message);
}
public InvalidInputException(Throwable cause) {
super(cause);
}
public InvalidInputException(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.wave.server.googleimport.conversion;
import org.waveprotocol.wave.model.document.operation.Attributes;
import org.waveprotocol.wave.model.document.operation.Nindo.NindoCursor;
import org.waveprotocol.wave.model.document.operation.NindoCursorDecorator;
import org.waveprotocol.wave.model.document.operation.impl.AttributesImpl;
import org.waveprotocol.wave.model.id.InvalidIdException;
import org.waveprotocol.wave.model.id.LegacyIdSerialiser;
import org.waveprotocol.wave.model.id.ModernIdSerialiser;
import org.waveprotocol.wave.model.util.CollectionUtils;
import org.waveprotocol.wave.model.util.StringMap;
import java.util.Map;
import java.util.logging.Logger;
/**
* Converts anchorWavelet attributes of the form googlewave.com!conv+root to
* googlewave.com/conv+root and similar, since WaveletBasedConversation expects
* the latter.
*
* @author ohler@google.com (Christian Ohler)
*/
public class PrivateReplyAnchorLegacyIdConverter extends NindoCursorDecorator {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(
PrivateReplyAnchorLegacyIdConverter.class.getName());
private final String documentId;
public PrivateReplyAnchorLegacyIdConverter(String documentId, NindoCursor target) {
super(target);
this.documentId = documentId;
}
@Override
public void elementStart(String type, Attributes attrs) {
if ("conversation".equals(documentId) && "conversation".equals(type)) {
StringMap<String> newAttrs = CollectionUtils.newStringMap();
for (Map.Entry<String, String> entry : attrs.entrySet()) {
if (!"anchorWavelet".equals(entry.getKey())) {
newAttrs.put(entry.getKey(), entry.getValue());
} else {
String newValue;
try {
newValue = ModernIdSerialiser.INSTANCE.serialiseWaveletId(
LegacyIdSerialiser.INSTANCE.deserialiseWaveletId(entry.getValue()));
} catch (InvalidIdException e) {
throw new InvalidInputException("Failed to convert anchorWavelet: " + attrs);
}
log.info("Replacing " + entry + " with value " + newValue);
newAttrs.put(entry.getKey(), newValue);
}
}
attrs = AttributesImpl.fromStringMap(newAttrs);
}
super.elementStart(type, attrs);
}
}
| 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.server.googleimport.conversion;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
import com.google.walkaround.proto.GoogleImport.GoogleDocument;
import com.google.walkaround.proto.GoogleImport.GoogleWavelet;
import com.google.walkaround.util.shared.Assert;
import org.waveprotocol.wave.model.document.operation.AnnotationBoundaryMap;
import org.waveprotocol.wave.model.document.operation.AnnotationBoundaryMapBuilder;
import org.waveprotocol.wave.model.document.operation.Attributes;
import org.waveprotocol.wave.model.document.operation.DocInitialization;
import org.waveprotocol.wave.model.document.operation.DocInitializationCursor;
import org.waveprotocol.wave.model.document.operation.DocOp;
import org.waveprotocol.wave.model.document.operation.impl.DocOpBuilder;
import org.waveprotocol.wave.model.document.operation.impl.DocOpUtil;
import org.waveprotocol.wave.model.id.IdUtil;
import org.waveprotocol.wave.model.operation.wave.AddParticipant;
import org.waveprotocol.wave.model.operation.wave.BlipContentOperation;
import org.waveprotocol.wave.model.operation.wave.NoOp;
import org.waveprotocol.wave.model.operation.wave.RemoveParticipant;
import org.waveprotocol.wave.model.operation.wave.WaveletBlipOperation;
import org.waveprotocol.wave.model.operation.wave.WaveletOperation;
import org.waveprotocol.wave.model.operation.wave.WaveletOperationContext;
import org.waveprotocol.wave.model.wave.InvalidParticipantAddress;
import org.waveprotocol.wave.model.wave.ParticipantId;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Synthesizes a history for a wavelet given a snapshot. Works for conversation
* wavelets and UDWs.
*
* @author ohler@google.com (Christian Ohler)
*/
public class HistorySynthesizer {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(HistorySynthesizer.class.getName());
public HistorySynthesizer() {
}
private static WaveletOperationContext getContext(String author, long timestampMillis) {
return new WaveletOperationContext(ParticipantId.ofUnsafe(author), timestampMillis, 1);
}
private static WaveletOperation newNoOp(String author, long timestampMillis) {
return new NoOp(getContext(author, timestampMillis));
}
public static WaveletOperation newAddParticipant(
String author, long timestampMillis, String userId) {
return new AddParticipant(getContext(author, timestampMillis), ParticipantId.ofUnsafe(userId));
}
public static WaveletOperation newRemoveParticipant(
String author, long timestampMillis, String userId) {
return new RemoveParticipant(getContext(author, timestampMillis),
ParticipantId.ofUnsafe(userId));
}
private WaveletOperation newMutateDocument(String author, long timestampMillis,
String documentId, DocOp op) {
return new WaveletBlipOperation(documentId,
new BlipContentOperation(getContext(author, timestampMillis), op));
}
private boolean containsAnnotationKey(DocInitialization content, final String key) {
final boolean[] found = { false };
content.apply(new DocInitializationCursor() {
@Override public void characters(String chars) {}
@Override public void elementStart(String type, Attributes attrs) {}
@Override public void elementEnd() {}
@Override public void annotationBoundary(AnnotationBoundaryMap map) {
for (int i = 0; i < map.changeSize(); i++) {
if (key.equals(map.getChangeKey(i))) {
found[0] = true;
}
}
}
});
return found[0];
}
// We produce worthy doc ops in pairs: first we set an annotation from null to
// "a", then we set it from "a" back to "null".
private DocOp newWorthyDocumentOperation(DocInitialization content, boolean first) {
int size = DocOpUtil.resultingDocumentLength(content);
String key = "walkaround-irrelevant-annotation-change-to-force-contribution";
while (containsAnnotationKey(content, key)) {
key += "1";
}
return new DocOpBuilder()
.annotationBoundary(
new AnnotationBoundaryMapBuilder().change(key,
first ? null : "a",
first ? "a" : null)
.build())
.retain(size)
.annotationBoundary(new AnnotationBoundaryMapBuilder().end(key).build())
.build();
}
private List<WaveletOperation> newWorthyContribution(String author, long timestampMillis,
String documentId, DocInitialization content) {
return ImmutableList.of(
newMutateDocument(author, timestampMillis, documentId,
newWorthyDocumentOperation(content, true)),
newMutateDocument(author, timestampMillis, documentId,
newWorthyDocumentOperation(content, false)));
}
private List<GoogleDocument> selectNonEmptyDocuments(List<GoogleDocument> docs) {
ImmutableList.Builder<GoogleDocument> out = ImmutableList.builder();
for (GoogleDocument doc : docs) {
if (DocOpUtil.resultingDocumentLength(
GoogleDeserializer.deserializeContent(doc.getContent())) > 0) {
out.add(doc);
}
}
return out.build();
}
private List<GoogleDocument> selectBlips(List<GoogleDocument> docs) {
ImmutableList.Builder<GoogleDocument> out = ImmutableList.builder();
for (GoogleDocument doc : docs) {
if (IdUtil.isBlipId(doc.getDocumentId())) {
out.add(doc);
}
}
return out.build();
}
private List<GoogleDocument> selectDataDocumentsExceptManifest(List<GoogleDocument> docs) {
ImmutableList.Builder<GoogleDocument> out = ImmutableList.builder();
for (GoogleDocument doc : docs) {
if (!IdUtil.isBlipId(doc.getDocumentId())
&& !IdUtil.isManifestDocument(doc.getDocumentId())) {
out.add(doc);
}
}
return out.build();
}
@Nullable private GoogleDocument selectManifest(List<GoogleDocument> docs) {
for (GoogleDocument doc : docs) {
if (IdUtil.isManifestDocument(doc.getDocumentId())) {
return doc;
}
}
return null;
}
private static Set<String> KNOWN_INVALID_ADDRESSES = ImmutableSet.of("<nobody>");
// Each string is nullable, the array itself is not.
private String pickValidParticipantId(@Nullable String... options) {
for (String s : options) {
if (s != null) {
try {
ParticipantId.of(s);
return s;
} catch (InvalidParticipantAddress e) {
if (!KNOWN_INVALID_ADDRESSES.contains(s)) {
log.info("Encountered invalid participant address: " + s);
}
}
}
}
throw new RuntimeException("No valid participant id: " + Arrays.toString(options));
}
private String getFirstContributor(GoogleDocument doc, GoogleWavelet w) {
Assert.check(doc.getContributorCount() > 0 || !IdUtil.isBlipId(doc.getDocumentId()),
"No contributors on blip %s: %s",
doc.getDocumentId(), doc.getContent());
return pickValidParticipantId(doc.getAuthor(),
doc.getContributorCount() == 0 ? null : doc.getContributor(0),
w.getCreator());
}
private List<GoogleDocument> sortedByLastModifiedTime(List<GoogleDocument> docs) {
List<GoogleDocument> out = Lists.newArrayList(docs);
Collections.sort(out, new Comparator<GoogleDocument>() {
@Override public int compare(GoogleDocument a, GoogleDocument b) {
return Ints.saturatedCast(a.getLastModifiedTimeMillis() - b.getLastModifiedTimeMillis());
}});
return out;
}
private void checkParticipantNormalized(String participantId) {
Assert.check(participantId.toLowerCase().equals(participantId),
"Participant id not normalized: %s", participantId);
}
private void checkParticipantsNormalized(GoogleWavelet w, List<GoogleDocument> docs) {
checkParticipantNormalized(w.getCreator());
for (String p : w.getParticipantList()) {
checkParticipantNormalized(p);
}
for (GoogleDocument doc : docs) {
checkParticipantNormalized(doc.getAuthor());
for (String p : doc.getContributorList()) {
checkParticipantNormalized(p);
}
}
}
private void checkLastModifiedTime(GoogleWavelet w, List<GoogleDocument> docs) {
long lastDocumentModificationTimeMillis = Long.MIN_VALUE;
for (GoogleDocument doc : docs) {
lastDocumentModificationTimeMillis = Math.max(lastDocumentModificationTimeMillis,
doc.getLastModifiedTimeMillis());
}
Assert.check(w.getLastModifiedTimeMillis() >= lastDocumentModificationTimeMillis,
"Wavelet last modified %s, last document %s",
w.getLastModifiedTimeMillis(), lastDocumentModificationTimeMillis);
}
private void checkDisjoint(List<?> a, List<?> b) {
// TODO(ohler): implement
}
private void checkNoDuplicates(List<?> list) {
// TODO(ohler): implement
}
// This will produce a history that looks like this:
// 1. (at creation time of the wavelet) the creator adds himself
// 2. (at creation time of the wavelet) the creator adds all other
// participants, in the order in which they are listed in the snapshot
// 3. (at creation time of the wavelet) the creator puts the content into all
// data documents except manifest, in unspecified order.
// 4. for each non-empty blip in arbitrary order:
// 4a. (at creation time of the wavelet) The author/first contributor of that
// blip sets the content.
// 4b. for each contributor on that blip:
// (at creation time of the wavelet) the contributor touches that blip
// with a worthy contribution (2 ops: one op that adds an unused
// annotation, a second op that removes it)
// 5. if the wavelet has a manifest:
// (at creation time of the wavelet) the creator adds the manifest
// 6. for each blip or data document, in last modified version order:
// (at last modification time of that document) the first contributor (or
// creator for data documents) touches the document with a worthy
// contribution.
// These changes become the new versions for UDW purposes -- we should
// record them somewhere.
// 7. (at last modified time of the wavelet) the creator adds a no-op
// 8. (at last modified time of the wavelet) the creator removes himself if
// he's not a participant
public List<WaveletOperation> synthesizeHistory(GoogleWavelet w, List<GoogleDocument> docs) {
checkNoDuplicates(docs);
docs = selectNonEmptyDocuments(docs);
checkParticipantsNormalized(w, docs);
checkNoDuplicates(w.getParticipantList());
checkLastModifiedTime(w, docs);
List<GoogleDocument> blipsInArbitraryOrder = selectBlips(docs);
List<GoogleDocument> dataDocsExceptManifestInArbitraryOrder =
selectDataDocumentsExceptManifest(docs);
@Nullable GoogleDocument manifest = selectManifest(docs);
checkDisjoint(blipsInArbitraryOrder, dataDocsExceptManifestInArbitraryOrder);
checkDisjoint(ImmutableList.of(manifest), blipsInArbitraryOrder);
checkDisjoint(ImmutableList.of(manifest), dataDocsExceptManifestInArbitraryOrder);
List<GoogleDocument> docsInLastModifiedTimeOrder = sortedByLastModifiedTime(docs);
List<WaveletOperation> history = Lists.newArrayList();
// 1
history.add(newAddParticipant(w.getCreator(), w.getCreationTimeMillis(), w.getCreator()));
// 2
for (String p : w.getParticipantList()) {
if (!p.equals(w.getCreator())) {
history.add(newAddParticipant(w.getCreator(), w.getCreationTimeMillis(), p));
}
}
// 3
for (GoogleDocument doc : dataDocsExceptManifestInArbitraryOrder) {
history.add(newMutateDocument(w.getCreator(), w.getCreationTimeMillis(),
doc.getDocumentId(), GoogleDeserializer.deserializeContent(doc.getContent())));
}
// 4
for (GoogleDocument doc : blipsInArbitraryOrder) {
Assert.check(IdUtil.isBlipId(doc.getDocumentId()));
DocInitialization content = GoogleDeserializer.deserializeContent(doc.getContent());
String docId = doc.getDocumentId();
// 4a
history.add(newMutateDocument(getFirstContributor(doc, w), w.getCreationTimeMillis(),
docId, content));
// 4b
for (String contributor : doc.getContributorList()) {
history.addAll(
newWorthyContribution(contributor, w.getCreationTimeMillis(), docId, content));
}
}
// 5
if (manifest != null) {
history.add(newMutateDocument(w.getCreator(), w.getCreationTimeMillis(),
manifest.getDocumentId(), GoogleDeserializer.deserializeContent(manifest.getContent())));
}
// 6
for (GoogleDocument doc : docsInLastModifiedTimeOrder) {
history.addAll(
newWorthyContribution(getFirstContributor(doc, w), doc.getLastModifiedTimeMillis(),
doc.getDocumentId(), GoogleDeserializer.deserializeContent(doc.getContent())));
}
// 7
history.add(newNoOp(w.getCreator(), w.getLastModifiedTimeMillis()));
// 8
if (!w.getParticipantList().contains(w.getCreator())) {
history.add(
newRemoveParticipant(w.getCreator(), w.getLastModifiedTimeMillis(), w.getCreator()));
}
return history;
}
}
| 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.server.googleimport.conversion;
import com.google.walkaround.proto.GoogleImport.GoogleDocumentContent;
import com.google.walkaround.proto.GoogleImport.GoogleDocumentContent.AnnotationBoundary;
import com.google.walkaround.proto.GoogleImport.GoogleDocumentContent.Component;
import com.google.walkaround.proto.GoogleImport.GoogleDocumentContent.ElementStart;
import com.google.walkaround.proto.GoogleImport.GoogleDocumentContent.KeyValuePair;
import com.google.walkaround.proto.GoogleImport.GoogleDocumentContent.KeyValueUpdate;
import org.waveprotocol.wave.model.document.operation.AnnotationBoundaryMap;
import org.waveprotocol.wave.model.document.operation.Attributes;
import org.waveprotocol.wave.model.document.operation.DocInitialization;
import org.waveprotocol.wave.model.document.operation.impl.AnnotationBoundaryMapImpl;
import org.waveprotocol.wave.model.document.operation.impl.AttributesImpl;
import org.waveprotocol.wave.model.document.operation.impl.DocInitializationBuilder;
import org.waveprotocol.wave.model.document.operation.util.ImmutableStateMap.Attribute;
import java.util.ArrayList;
import java.util.List;
/**
* Turns Google legacy protobufs into model objects.
*
* @author ohler@google.com (Christian Ohler)
*/
public class GoogleDeserializer {
private GoogleDeserializer() {}
private static Attributes attributesFrom(ElementStart in) {
List<Attribute> attributes = new ArrayList<Attribute>();
for (KeyValuePair p : in.getAttributeList()) {
attributes.add(new Attribute(p.getKey(), p.getValue()));
}
try {
return AttributesImpl.fromSortedAttributes(attributes);
} catch (IllegalArgumentException e) {
throw new InvalidInputException("Invalid attributes: " + e, e);
}
}
private static AnnotationBoundaryMap annotationBoundaryFrom(AnnotationBoundary in) {
String[] endKeys = new String[in.getEndCount()];
String[] changeKeys = new String[in.getChangeCount()];
String[] changeOldValues = new String[in.getChangeCount()];
String[] changeNewValues = new String[in.getChangeCount()];
for (int i = 0; i < endKeys.length; i++) {
endKeys[i] = in.getEnd(i);
}
for (int i = 0; i < changeKeys.length; i++) {
KeyValueUpdate change = in.getChange(i);
changeKeys[i] = change.getKey();
changeOldValues[i] = change.hasOldValue() ? change.getOldValue() : null;
changeNewValues[i] = change.hasNewValue() ? change.getNewValue() : null;
}
try {
return AnnotationBoundaryMapImpl.builder()
.initializationEnd(endKeys)
.updateValues(changeKeys, changeOldValues, changeNewValues)
.build();
} catch (IllegalArgumentException e) {
throw new InvalidInputException("Invalid annotation boundary: " + e, e);
}
}
private static void applyComponent(Component component, DocInitializationBuilder out) {
if (component.hasAnnotationBoundary()) {
out.annotationBoundary(annotationBoundaryFrom(component.getAnnotationBoundary()));
} else if (component.hasCharacters()) {
out.characters(component.getCharacters());
} else if (component.hasElementStart()) {
ElementStart elementStart = component.getElementStart();
out.elementStart(elementStart.getType(), attributesFrom(elementStart));
} else if (component.hasElementEnd()) {
if (!component.getElementEnd()) {
throw new InvalidInputException("Element end present but false: " + component);
}
out.elementEnd();
} else {
throw new InvalidInputException("Fell through in applyComponent: " + component);
}
}
public static DocInitialization deserializeContent(GoogleDocumentContent in) {
DocInitializationBuilder out = new DocInitializationBuilder();
for (Component component : in.getComponentList()) {
applyComponent(component, out);
}
return out.build();
}
}
| 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.server.googleimport.conversion;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Function;
import org.waveprotocol.wave.model.document.indexed.IndexedDocument;
import org.waveprotocol.wave.model.document.operation.DocInitialization;
import org.waveprotocol.wave.model.document.operation.DocOp;
import org.waveprotocol.wave.model.document.operation.Nindo;
import org.waveprotocol.wave.model.document.raw.impl.Element;
import org.waveprotocol.wave.model.document.raw.impl.Node;
import org.waveprotocol.wave.model.document.raw.impl.Text;
import org.waveprotocol.wave.model.document.util.DocProviders;
import org.waveprotocol.wave.model.operation.OperationException;
import org.waveprotocol.wave.model.util.Pair;
/**
* @author danilatos@google.com (Daniel Danilatos)
*/
public class DocumentHistoryConverter {
private final String documentId;
private final Function<Pair<String, Nindo>, Nindo> nindoConverter;
private final IndexedDocument<Node, Element, Text> doc = DocProviders.POJO.parse("");
public DocumentHistoryConverter(String documentId,
Function<Pair<String, Nindo>, Nindo> nindoConverter) {
this.documentId = checkNotNull(documentId, "Null documentId");
this.nindoConverter = checkNotNull(nindoConverter, "Null nindoConverter");
}
public DocOp convertAndApply(Nindo old) throws OperationException {
return doc.consumeAndReturnInvertible(nindoConverter.apply(Pair.of(documentId, old)));
}
public DocOp convertAndApply(DocOp old) throws OperationException {
return convertAndApply(Nindo.fromDocOp(old, false));
}
public DocInitialization getCurrentState() {
return doc.asOperation();
}
}
| 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.server.googleimport.conversion;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.walkaround.wave.server.attachment.AttachmentId;
import org.waveprotocol.wave.model.document.operation.AnnotationBoundaryMap;
import org.waveprotocol.wave.model.document.operation.Attributes;
import org.waveprotocol.wave.model.document.operation.AttributesUpdate;
import org.waveprotocol.wave.model.document.operation.DocOpCursor;
import org.waveprotocol.wave.model.document.operation.Nindo.NindoCursor;
import org.waveprotocol.wave.model.document.operation.NindoCursorDecorator;
import org.waveprotocol.wave.model.document.operation.impl.AttributesImpl;
import org.waveprotocol.wave.model.operation.wave.AddParticipant;
import org.waveprotocol.wave.model.operation.wave.BlipContentOperation;
import org.waveprotocol.wave.model.operation.wave.BlipOperationVisitor;
import org.waveprotocol.wave.model.operation.wave.NoOp;
import org.waveprotocol.wave.model.operation.wave.RemoveParticipant;
import org.waveprotocol.wave.model.operation.wave.SubmitBlip;
import org.waveprotocol.wave.model.operation.wave.VersionUpdateOp;
import org.waveprotocol.wave.model.operation.wave.WaveletBlipOperation;
import org.waveprotocol.wave.model.operation.wave.WaveletOperation;
import org.waveprotocol.wave.model.operation.wave.WaveletOperationVisitor;
import org.waveprotocol.wave.model.util.CollectionUtils;
import org.waveprotocol.wave.model.util.StringMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
/**
* Converts attachment ids. Needs to run after the converter that strips the
* "w:" prefixes.
*
* @author ohler@google.com (Christian Ohler)
*/
public class AttachmentIdConverter extends NindoCursorDecorator {
private static final String ATTACHMENT_ID_ATTRIBUTE_NAME = "attachment";
private static final String IMAGE_ELEMENT_TYPE = "image";
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(AttachmentIdConverter.class.getName());
private final Map<String, AttachmentId> mapping;
public AttachmentIdConverter(Map<String, AttachmentId> mapping,
NindoCursor target) {
super(target);
this.mapping = mapping;
}
@Override
public void elementStart(String type, Attributes attrs) {
if (IMAGE_ELEMENT_TYPE.equals(type)) {
StringMap<String> newAttrs = CollectionUtils.newStringMap();
for (Map.Entry<String, String> entry : attrs.entrySet()) {
if (!ATTACHMENT_ID_ATTRIBUTE_NAME.equals(entry.getKey())) {
newAttrs.put(entry.getKey(), entry.getValue());
} else {
String newValue;
AttachmentId mapped = mapping.get(entry.getValue());
if (mapped == null) {
log.warning("Attachment id not found: " + entry);
// Preserve; not sure this is a good idea but it's probably better
// than dropping the value.
newValue = entry.getValue();
} else {
log.info("Replacing " + entry + " with value " + mapped);
newValue = mapped.getId();
}
newAttrs.put(entry.getKey(), newValue);
}
}
attrs = AttributesImpl.fromStringMap(newAttrs);
}
super.elementStart(type, attrs);
}
// TODO(ohler): currently unused; consider deleting
public static Set<String> findAttachmentIds(List<WaveletOperation> history) {
final Set<String> out = Sets.newHashSet();
for (WaveletOperation op : history) {
op.acceptVisitor(new WaveletOperationVisitor() {
@Override public void visitNoOp(NoOp op) {}
@Override public void visitVersionUpdateOp(VersionUpdateOp op) {
throw new AssertionError("Unexpected visitVersionUpdateOp(" + op + ")");
}
@Override public void visitAddParticipant(AddParticipant op) {}
@Override public void visitRemoveParticipant(RemoveParticipant op) {}
@Override public void visitWaveletBlipOperation(final WaveletBlipOperation waveletOp) {
waveletOp.getBlipOp().acceptVisitor(new BlipOperationVisitor() {
@Override public void visitBlipContentOperation(BlipContentOperation blipOp) {
blipOp.getContentOp().apply(new DocOpCursor() {
@Override public void annotationBoundary(AnnotationBoundaryMap m) {}
@Override public void characters(String chars) {}
@Override public void elementEnd() {}
@Override public void deleteCharacters(String chars) {}
@Override public void deleteElementEnd() {}
@Override public void replaceAttributes(Attributes a, Attributes b) {}
@Override public void retain(int count) {}
@Override public void updateAttributes(AttributesUpdate update) {}
@Override public void elementStart(String type, Attributes attrs) {
if (IMAGE_ELEMENT_TYPE.equals(type)) {
for (Map.Entry<String, String> entry : attrs.entrySet()) {
if (!ATTACHMENT_ID_ATTRIBUTE_NAME.equals(entry.getKey())) {
out.add(entry.getValue());
}
}
}
}
@Override public void deleteElementStart(String type, Attributes attrs) {
// We can ignore this since any attachment ids must also be in the
// corresponding elementStart().
}
});
}
@Override public void visitSubmitBlip(SubmitBlip blipOp) {
throw new AssertionError("Unexpected visitSubmitBlip(" + blipOp + ")");
}
});
}
});
}
return ImmutableSet.copyOf(out);
}
}
| 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.server.googleimport.conversion;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.MapMaker;
import com.google.walkaround.util.shared.Assert;
import org.waveprotocol.wave.model.document.operation.DocOp;
import org.waveprotocol.wave.model.document.operation.Nindo;
import org.waveprotocol.wave.model.operation.OperationException;
import org.waveprotocol.wave.model.operation.wave.AddParticipant;
import org.waveprotocol.wave.model.operation.wave.BlipContentOperation;
import org.waveprotocol.wave.model.operation.wave.BlipOperationVisitor;
import org.waveprotocol.wave.model.operation.wave.NoOp;
import org.waveprotocol.wave.model.operation.wave.RemoveParticipant;
import org.waveprotocol.wave.model.operation.wave.SubmitBlip;
import org.waveprotocol.wave.model.operation.wave.VersionUpdateOp;
import org.waveprotocol.wave.model.operation.wave.WaveletBlipOperation;
import org.waveprotocol.wave.model.operation.wave.WaveletOperation;
import org.waveprotocol.wave.model.operation.wave.WaveletOperationContext;
import org.waveprotocol.wave.model.operation.wave.WaveletOperationVisitor;
import org.waveprotocol.wave.model.util.Pair;
import java.util.Map;
/**
* Converts a wavelet history by using a {@link DocumentHistoryConverter} for
* each document.
*
* @author ohler@google.com (Christian Ohler)
*/
public class WaveletHistoryConverter {
// 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, DocumentHistoryConverter> docConverters =
new MapMaker().makeComputingMap(
new Function<String, DocumentHistoryConverter>() {
@Override public DocumentHistoryConverter apply(String documentId) {
return new DocumentHistoryConverter(documentId, nindoConverter);
}
});
private final Function<Pair<String, Nindo>, Nindo> nindoConverter;
public WaveletHistoryConverter(Function<Pair<String, Nindo>, Nindo> nindoConverter) {
this.nindoConverter = checkNotNull(nindoConverter, "Null nindoConverter");
}
public WaveletOperation convertAndApply(final WaveletOperation op) {
final WaveletOperation[] result = { null };
op.acceptVisitor(new WaveletOperationVisitor() {
void setResult(WaveletOperation x) {
Preconditions.checkState(result[0] == null,
"%s: More than one result: %s, %s", op, result[0], x);
result[0] = x;
}
@Override public void visitNoOp(NoOp op) {
setResult(op);
}
@Override public void visitVersionUpdateOp(VersionUpdateOp op) {
throw new AssertionError("Unexpected visitVersionUpdateOp(" + op + ")");
}
@Override public void visitAddParticipant(AddParticipant op) {
setResult(op);
}
@Override public void visitRemoveParticipant(RemoveParticipant op) {
setResult(op);
}
@Override public void visitWaveletBlipOperation(final WaveletBlipOperation waveletOp) {
final String documentId = waveletOp.getBlipId();
final WaveletOperationContext context = waveletOp.getContext();
waveletOp.getBlipOp().acceptVisitor(new BlipOperationVisitor() {
@Override public void visitBlipContentOperation(BlipContentOperation blipOp) {
DocOp converted;
try {
converted = docConverters.get(documentId).convertAndApply(blipOp.getContentOp());
} catch (OperationException e) {
throw new InvalidInputException("OperationException converting " + waveletOp, e);
}
setResult(new WaveletBlipOperation(
documentId, new BlipContentOperation(context, converted)));
}
@Override public void visitSubmitBlip(SubmitBlip blipOp) {
throw new AssertionError("Unexpected visitSubmitBlip(" + blipOp + ")");
}
});
}
});
Assert.check(result[0] != null, "No result: %s", op);
return result[0];
}
}
| 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.server.googleimport.conversion;
import org.waveprotocol.wave.model.document.operation.Attributes;
import org.waveprotocol.wave.model.document.operation.Nindo.NindoCursor;
import org.waveprotocol.wave.model.document.operation.NindoCursorDecorator;
import java.util.logging.Logger;
/**
* Strips the "w:" prefix from elements.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class StripWColonFilter extends NindoCursorDecorator {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(StripWColonFilter.class.getName());
public StripWColonFilter(NindoCursor target) {
super(target);
}
@Override
public void elementStart(String type, Attributes attrs) {
super.elementStart(strip(type), attrs);
}
private String strip(String type) {
return type.startsWith("w:") ? type.substring(2) : type;
}
}
| 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.server.googleimport;
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.appengine.api.datastore.Text;
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.Lists;
import com.google.common.collect.Maps;
import com.google.inject.Inject;
import com.google.walkaround.proto.ImportTaskPayload;
import com.google.walkaround.proto.RobotSearchDigest;
import com.google.walkaround.proto.gson.ImportTaskPayloadGsonImpl;
import com.google.walkaround.proto.gson.RobotSearchDigestGsonImpl;
import com.google.walkaround.slob.server.GsonProto;
import com.google.walkaround.slob.shared.MessageException;
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.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 com.google.walkaround.wave.server.WalkaroundServletModule;
import com.google.walkaround.wave.server.auth.StableUserId;
import com.google.walkaround.wave.server.gxp.SourceInstance;
import org.waveprotocol.wave.model.id.WaveId;
import org.waveprotocol.wave.model.id.WaveletId;
import org.waveprotocol.wave.model.id.WaveletName;
import org.waveprotocol.wave.model.util.Pair;
import org.waveprotocol.wave.model.util.ValueUtils;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Holds data about import status. All data that should be stored in one entity
* group per user goes into this table.
*
* @author ohler@google.com (Christian Ohler)
*/
public class PerUserTable {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(PerUserTable.class.getName());
private static final String ROOT_ENTITY_KIND = "ImportUser";
private static final String WAVELET_ENTITY_KIND = "ImportWavelet";
private static final String WAVELET_DIGEST_PROPERTY = "digest";
// Last modified time is also stored in the digest but we put it in a separate
// property as well so that we can have an index on it.
private static final String WAVELET_LAST_MODIFIED_MILLIS_PROPERTY = "lastModified";
private static final String WAVELET_PRIVATE_LOCAL_ID_PROPERTY = "privateLocalId";
private static final String WAVELET_SHARED_LOCAL_ID_PROPERTY = "sharedLocalId";
private static final String TASK_ENTITY_KIND = "ImportTask4";
private static final String TASK_CREATION_TIME_MILLIS_PROPERTY = "created";
private static final String TASK_PAYLOAD_PROPERTY = "payload";
private final SourceInstance.Factory sourceInstanceFactory;
private final Queue taskQueue;
@Inject
public PerUserTable(SourceInstance.Factory sourceInstanceFactory,
@ImportTaskQueue Queue taskQueue) {
this.sourceInstanceFactory = sourceInstanceFactory;
this.taskQueue = taskQueue;
}
private Key makeRootKey(StableUserId userId) {
return KeyFactory.createKey(ROOT_ENTITY_KIND, userId.getId());
}
private Pair<SourceInstance, WaveletName> parseWaveletKeyString(String key) {
String[] components = key.split(" ", -1);
Assert.check(components.length == 3, "Wrong number of spaces: %s", key);
return Pair.of(
sourceInstanceFactory.parseUnchecked(components[0]),
WaveletName.of(WaveId.deserialise(components[1]),
WaveletId.deserialise(components[2])));
}
private String makeWaveletKeyString(SourceInstance sourceInstance, WaveletName waveletName) {
// By design, wave ids should be unique across all instances, but it's easy
// not to rely on this, so let's not.
String key = sourceInstance.serialize()
+ " " + waveletName.waveId.serialise() + " " + waveletName.waveletId.serialise();
Assert.check(Pair.of(sourceInstance, waveletName).equals(parseWaveletKeyString(key)),
"Failed to serialize: %s, %s", sourceInstance, waveletName);
return key;
}
private Pair<SourceInstance, WaveletName> parseWaveletKey(Key key) {
return parseWaveletKeyString(key.getName());
}
private Key makeWaveletKey(StableUserId userId, SourceInstance sourceInstance,
WaveletName waveletName) {
return KeyFactory.createKey(makeRootKey(userId),
WAVELET_ENTITY_KIND, makeWaveletKeyString(sourceInstance, waveletName));
}
private Key makeTaskKey(StableUserId userId, long taskId) {
return KeyFactory.createKey(makeRootKey(userId), TASK_ENTITY_KIND, taskId);
}
private RemoteConvWavelet parseWaveletEntity(Entity entity) {
Pair<SourceInstance, WaveletName> instanceAndWaveId = parseWaveletKey(entity.getKey());
try {
RobotSearchDigest digest = GsonProto.fromGson(new RobotSearchDigestGsonImpl(),
DatastoreUtil.getExistingProperty(entity, WAVELET_DIGEST_PROPERTY, Text.class)
.getValue());
Assert.check(
instanceAndWaveId.getSecond().waveId.equals(WaveId.deserialise(digest.getWaveId())),
"Wave id mismatch: %s, %s", instanceAndWaveId, entity);
Assert.check(DatastoreUtil.getExistingProperty(
entity, WAVELET_LAST_MODIFIED_MILLIS_PROPERTY, Long.class)
.equals(digest.getLastModifiedMillis()),
"Mismatched last modified times: %s, %s", digest, entity);
@Nullable String privateLocalId = DatastoreUtil.getOptionalProperty(
entity, WAVELET_PRIVATE_LOCAL_ID_PROPERTY, String.class);
@Nullable String sharedLocalId = DatastoreUtil.getOptionalProperty(
entity, WAVELET_SHARED_LOCAL_ID_PROPERTY, String.class);
return new RemoteConvWavelet(instanceAndWaveId.getFirst(), digest,
instanceAndWaveId.getSecond().waveletId,
privateLocalId == null ? null : new SlobId(privateLocalId),
sharedLocalId == null ? null : new SlobId(sharedLocalId));
} catch (MessageException e) {
throw new RuntimeException("Failed to parse wave entity: " + entity, e);
}
}
private WaveletName getWaveletName(RemoteConvWavelet w) {
return WaveletName.of(WaveId.deserialise(w.getDigest().getWaveId()), w.getWaveletId());
}
private Entity serializeWavelet(StableUserId userId, RemoteConvWavelet w) {
Key key = makeWaveletKey(userId, w.getSourceInstance(), getWaveletName(w));
Entity e = new Entity(key);
DatastoreUtil.setNonNullUnindexedProperty(e, WAVELET_DIGEST_PROPERTY,
new Text(GsonProto.toJson((RobotSearchDigestGsonImpl) w.getDigest())));
DatastoreUtil.setNonNullIndexedProperty(e, WAVELET_LAST_MODIFIED_MILLIS_PROPERTY,
w.getDigest().getLastModifiedMillis());
DatastoreUtil.setOrRemoveIndexedProperty(e, WAVELET_PRIVATE_LOCAL_ID_PROPERTY,
w.getPrivateLocalId() == null ? null : w.getPrivateLocalId().getId());
DatastoreUtil.setOrRemoveIndexedProperty(e, WAVELET_SHARED_LOCAL_ID_PROPERTY,
w.getSharedLocalId() == null ? null : w.getSharedLocalId().getId());
// Sanity check.
Assert.check(w.equals(parseWaveletEntity(e)), "Serialized %s incorrectly: %s", w, e);
return e;
}
private ImportTask parseTaskEntity(Entity entity) {
long taskId = entity.getKey().getId();
StableUserId userId = new StableUserId(entity.getParent().getName());
try {
return new ImportTask(userId, taskId,
DatastoreUtil.getExistingProperty(entity, TASK_CREATION_TIME_MILLIS_PROPERTY, Long.class),
GsonProto.fromGson(new ImportTaskPayloadGsonImpl(),
DatastoreUtil.getExistingProperty(entity, TASK_PAYLOAD_PROPERTY, Text.class)
.getValue()));
} catch (MessageException e) {
throw new RuntimeException("Failed to parse task entity: " + entity, e);
}
}
// Returns an entity with an incomplete key (the datastore will fill in an auto-allocated id).
private Entity serializeTask(
StableUserId userId, long creationTimeMillis, ImportTaskPayload payload) {
Entity entity = new Entity(TASK_ENTITY_KIND, makeRootKey(userId));
DatastoreUtil.setNonNullIndexedProperty(entity, TASK_CREATION_TIME_MILLIS_PROPERTY,
creationTimeMillis);
DatastoreUtil.setNonNullUnindexedProperty(entity, TASK_PAYLOAD_PROPERTY,
new Text(GsonProto.toJson((ImportTaskPayloadGsonImpl) payload)));
// Can't deserialize for sanity check here since the key is incomplete. But
// our caller can do the sanity check after put() completes the key.
return entity;
}
/**
* Adds the given remote waves.
*
* Returns true if any entities were put (i.e., if a commit is needed), false
* otherwise.
*/
public boolean addRemoteWavelets(
CheckedTransaction tx, StableUserId userId,
List<RemoteConvWavelet> convWavelets) throws RetryableFailure, PermanentFailure {
log.info("Adding " + convWavelets.size() + " digests");
List<Key> keys = Lists.newArrayList();
for (RemoteConvWavelet convWavelet : convWavelets) {
keys.add(
makeWaveletKey(userId, convWavelet.getSourceInstance(), getWaveletName(convWavelet)));
}
Map<Key, Entity> existingEntities = tx.get(keys);
Map<Key, Entity> entitiesToPut = Maps.newHashMapWithExpectedSize(convWavelets.size());
int newCount = 0;
int unchangedCount = 0;
int updatedCount = 0;
for (RemoteConvWavelet convWavelet : convWavelets) {
Key key =
makeWaveletKey(userId, convWavelet.getSourceInstance(), getWaveletName(convWavelet));
Entity existingEntity = existingEntities.get(key);
if (existingEntity == null) {
entitiesToPut.put(key, serializeWavelet(userId, convWavelet));
newCount++;
} else {
RemoteConvWavelet existing = parseWaveletEntity(existingEntity);
Assert.check(convWavelet.getSourceInstance().equals(existing.getSourceInstance())
&& convWavelet.getWaveletId().equals(existing.getWaveletId()),
"%s, %s", convWavelet, existing);
RemoteConvWavelet merged = new RemoteConvWavelet(convWavelet.getSourceInstance(),
convWavelet.getDigest(),
convWavelet.getWaveletId(),
existing.getPrivateLocalId(),
existing.getSharedLocalId());
if (merged.equals(existing)) {
// Wavelet unchanged, do nothing.
unchangedCount++;
} else {
// TODO(ohler): Fix PST protobuf toString() method to be meaningful.
log.info("Updating existing wavelet " + key + ": " + existing
+ " updated with " + convWavelet + " becomes " + merged);
entitiesToPut.put(key, serializeWavelet(userId, merged));
updatedCount++;
}
}
}
if (entitiesToPut.isEmpty()) {
return false;
}
log.info(newCount + " new, " + updatedCount + " updated, "
+ unchangedCount + " unchanged; putting " + entitiesToPut.size() + " entities: "
+ ValueUtils.abbrev("" + entitiesToPut, 500));
tx.put(entitiesToPut.values());
return true;
}
@Nullable public RemoteConvWavelet getWavelet(CheckedTransaction tx,
StableUserId userId, SourceInstance instance, WaveletName waveletName)
throws RetryableFailure, PermanentFailure {
log.info("getWavelet(" + userId + ", " + instance + ", " + waveletName + ")");
Entity entity = tx.get(makeWaveletKey(userId, instance, waveletName));
RemoteConvWavelet wavelet = entity == null ? null : parseWaveletEntity(entity);
log.info("Got " + wavelet);
return wavelet;
}
@Nullable public void putWavelet(CheckedTransaction tx,
StableUserId userId, RemoteConvWavelet wavelet) throws RetryableFailure, PermanentFailure {
log.info("putWavelet(" + userId + ", " + wavelet + ")");
Entity entity = serializeWavelet(userId, wavelet);
log.info("Putting " + wavelet);
tx.put(entity);
}
// TODO(ohler): make this scalable, e.g. by adding pagination
public List<RemoteConvWavelet> getAllWavelets(CheckedTransaction tx, StableUserId userId)
throws RetryableFailure, PermanentFailure {
log.info("getAllWaves(" + userId + ")");
CheckedIterator i = tx.prepare(new Query(WAVELET_ENTITY_KIND)
.setAncestor(makeRootKey(userId))
.addSort(WAVELET_LAST_MODIFIED_MILLIS_PROPERTY, Query.SortDirection.DESCENDING))
.asIterator();
ImmutableList.Builder<RemoteConvWavelet> b = ImmutableList.builder();
while (i.hasNext()) {
b.add(parseWaveletEntity(i.next()));
}
List<RemoteConvWavelet> out = b.build();
log.info("Got " + out.size() + " wavelets");
return out;
}
// Among other things, mutates q to make it keys-only.
private boolean deleteAll(CheckedTransaction tx, Query q)
throws RetryableFailure, PermanentFailure {
q.setKeysOnly();
CheckedIterator i = tx.prepare(q).asIterator();
if (!i.hasNext()) {
return false;
}
while (i.hasNext()) {
tx.delete(i.next().getKey());
}
return true;
}
// TODO(ohler): make this scalable, by deleting in chunks, or through the task queue
/** Returns true if any entities have been deleted (i.e., tx needs to be committed. */
public boolean deleteAllWaves(CheckedTransaction tx, StableUserId userId)
throws RetryableFailure, PermanentFailure {
log.info("deleteAllWaves(" + userId + ")");
return deleteAll(tx, new Query(WAVELET_ENTITY_KIND).setAncestor(makeRootKey(userId)));
}
/** Returns true if any entities have been deleted (i.e., tx needs to be committed. */
public boolean deleteAllTasks(CheckedTransaction tx, StableUserId userId)
throws RetryableFailure, PermanentFailure {
log.info("deleteAllTasks(" + userId + ")");
return deleteAll(tx, new Query(TASK_ENTITY_KIND).setAncestor(makeRootKey(userId)));
}
public ImportTask addTask(CheckedTransaction tx, StableUserId userId, ImportTaskPayload payload)
throws RetryableFailure, PermanentFailure {
Entity entity = serializeTask(userId, System.currentTimeMillis(), payload);
tx.put(entity);
// Sanity check, and retrieve ID.
ImportTask written = parseTaskEntity(entity);
Assert.check(userId.equals(written.getUserId()), "User id mismatch: %s, %s", userId, written);
Assert.check(payload.equals(written.getPayload()),
"Payload mismatch: %s, %s", payload, written);
tx.enqueueTask(taskQueue,
TaskOptions.Builder.withUrl(WalkaroundServletModule.IMPORT_TASK_PATH)
.method(TaskOptions.Method.POST)
.param(ImportTaskHandler.USER_ID_HEADER, userId.getId())
.param(ImportTaskHandler.TASK_ID_HEADER, "" + written.getTaskId()));
return written;
}
public List<ImportTask> getAllTasks(CheckedTransaction tx, StableUserId userId)
throws RetryableFailure, PermanentFailure {
log.info("getAllTasks(" + userId + ")");
CheckedIterator i = tx.prepare(new Query(TASK_ENTITY_KIND)
.setAncestor(makeRootKey(userId))
.addSort(Entity.KEY_RESERVED_PROPERTY, Query.SortDirection.ASCENDING))
.asIterator();
ImmutableList.Builder<ImportTask> b = ImmutableList.builder();
while (i.hasNext()) {
b.add(parseTaskEntity(i.next()));
}
List<ImportTask> out = b.build();
log.info("Got " + out.size() + " tasks");
return out;
}
@Nullable public ImportTask getTask(CheckedTransaction tx, StableUserId userId, long taskId)
throws RetryableFailure, PermanentFailure {
log.info("getTask(" + userId + ", " + taskId + ")");
Entity entity = tx.get(makeTaskKey(userId, taskId));
ImportTask task = entity == null ? null : parseTaskEntity(entity);
log.info("Got " + task);
return task;
}
public void deleteTask(CheckedTransaction tx, StableUserId userId, long taskId)
throws RetryableFailure, PermanentFailure {
log.info("deleteTask(" + userId + ", " + taskId + ")");
tx.delete(makeTaskKey(userId, taskId));
}
}
| 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.server.googleimport;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.Multimap;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.walkaround.proto.FetchAttachmentsAndImportWaveletTask;
import com.google.walkaround.proto.FindRemoteWavesTask;
import com.google.walkaround.proto.ImportTaskPayload;
import com.google.walkaround.proto.ImportWaveletTask;
import com.google.walkaround.proto.ImportSettings.ImportSharingMode;
import com.google.walkaround.util.server.RetryHelper.PermanentFailure;
import com.google.walkaround.wave.server.gxp.SourceInstance;
import org.waveprotocol.wave.model.id.WaveId;
import org.waveprotocol.wave.model.id.WaveletId;
import org.waveprotocol.wave.model.id.WaveletName;
import org.waveprotocol.wave.model.util.Pair;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
/**
* Knows about different task types and how to operate on them.
*
* @author ohler@google.com (Christian Ohler)
*/
public class TaskDispatcher {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(TaskDispatcher.class.getName());
private final SourceInstance.Factory sourceInstanceFactory;
// Providers because most paths will need only one.
private final Provider<FindRemoteWavesProcessor> findWavesProcessor;
private final Provider<ImportWaveletProcessor> importWaveProcessor;
private final Provider<FetchAttachmentsProcessor> fetchAttachmentsProcessor;
@Inject
public TaskDispatcher(SourceInstance.Factory sourceInstanceFactory,
Provider<FindRemoteWavesProcessor> findWavesProcessor,
Provider<ImportWaveletProcessor> importWaveProcessor,
Provider<FetchAttachmentsProcessor> fetchAttachmentsProcessor) {
this.sourceInstanceFactory = sourceInstanceFactory;
this.findWavesProcessor = findWavesProcessor;
this.importWaveProcessor = importWaveProcessor;
this.fetchAttachmentsProcessor = fetchAttachmentsProcessor;
}
private String taskAgePrefix(ImportTask task) {
long age = System.currentTimeMillis() - task.getCreationTimeMillis();
long secs = age / 1000;
long minutes = secs / 60;
long hours = minutes / 60;
long days = hours / 24;
if (days > 1) {
return "(over " + days + " days old) ";
} else if (hours > 1) {
return "(over " + hours + " hours old) ";
} else if (minutes > 5) {
return "(over " + minutes + " minutes old) ";
} else {
// Not worth mentioning.
return "";
}
}
public String describeTask(ImportTask task) {
if (task.getPayload().hasFindWavesTask()) {
FindRemoteWavesTask t = task.getPayload().getFindWavesTask();
return taskAgePrefix(task)
+ (t.hasAutoImportSettings() ? "Find and import" : "Find") + " waves on "
+ sourceInstanceFactory.parseUnchecked(t.getInstance()).getShortName()
+ " between " + DaysSinceEpoch.toLocalDate(t.getOnOrAfterDays())
+ " and " + DaysSinceEpoch.toLocalDate(t.getBeforeDays());
} else if (task.getPayload().hasImportWaveletTask()) {
ImportWaveletTask t = task.getPayload().getImportWaveletTask();
String sharingMode;
switch (t.getSettings().getSharingMode()) {
case PRIVATE:
sharingMode = "Private";
break;
case SHARED:
sharingMode = "Shared";
break;
case PRIVATE_UNLESS_PARTICIPANT:
sharingMode = "Shared (if participant)";
break;
default:
throw new AssertionError("Unexpected SharingMode: " + t.getSettings().getSharingMode());
}
return taskAgePrefix(task)
+ sharingMode + " import of wavelet " + t.getWaveId() + " " + t.getWaveletId()
+ " from " + sourceInstanceFactory.parseUnchecked(t.getInstance()).getShortName();
} else if (task.getPayload().hasFetchAttachmentsTask()) {
FetchAttachmentsAndImportWaveletTask t = task.getPayload().getFetchAttachmentsTask();
return taskAgePrefix(task)
+ " Fetch attachments for wavelet "
+ t.getOriginalImportTask().getWaveId() + " " + t.getOriginalImportTask().getWaveletId()
+ " from " + sourceInstanceFactory.parseUnchecked(
t.getOriginalImportTask().getInstance()).getShortName()
+ " (" + t.getImportedSize() + "/" + (t.getImportedSize() + t.getToImportSize()) + ")";
} else {
throw new AssertionError("Unknown task payload type: " + task);
}
}
public boolean importAllInProgress(List<ImportTask> tasksInProgress) {
for (ImportTask task : tasksInProgress) {
if (task.getPayload().hasFindWavesTask()) {
if (task.getPayload().getFindWavesTask().hasAutoImportSettings()) {
return true;
}
}
}
return false;
}
public Multimap<Pair<SourceInstance, WaveletName>, ImportSharingMode> waveletImportsInProgress(
List<ImportTask> tasksInProgress) {
ImmutableSetMultimap.Builder<Pair<SourceInstance, WaveletName>, ImportSharingMode> out =
ImmutableSetMultimap.builder();
for (ImportTask task : tasksInProgress) {
if (task.getPayload().hasFindWavesTask()) {
// nothing
} else {
ImportWaveletTask t;
if (task.getPayload().hasFetchAttachmentsTask()) {
t = task.getPayload().getFetchAttachmentsTask().getOriginalImportTask();
} else if (task.getPayload().hasImportWaveletTask()) {
t = task.getPayload().getImportWaveletTask();
} else {
throw new AssertionError("Unknown task payload type: " + task);
}
out.put(
Pair.of(sourceInstanceFactory.parseUnchecked(t.getInstance()),
WaveletName.of(WaveId.deserialise(t.getWaveId()),
WaveletId.deserialise(t.getWaveletId()))),
t.getSettings().getSharingMode());
}
}
return out.build();
}
private boolean exactlyOneTrue(Boolean... args) {
return Collections.frequency(Arrays.asList(args), true) == 1;
}
public List<ImportTaskPayload> processTask(ImportTask task) throws IOException {
Preconditions.checkArgument(exactlyOneTrue(
task.getPayload().hasFindWavesTask(),
task.getPayload().hasImportWaveletTask(),
task.getPayload().hasFetchAttachmentsTask()),
"Need exactly one type of payload: %s", task);
try {
if (task.getPayload().hasFindWavesTask()) {
return findWavesProcessor.get().findWaves(task.getPayload().getFindWavesTask());
} else if (task.getPayload().hasImportWaveletTask()) {
return importWaveProcessor.get().importWavelet(task.getPayload().getImportWaveletTask());
} else if (task.getPayload().hasFetchAttachmentsTask()) {
return fetchAttachmentsProcessor.get()
.fetchAttachments(task.getPayload().getFetchAttachmentsTask());
} else {
throw new AssertionError("Unknown task payload type: " + task);
}
} catch (PermanentFailure e) {
throw new IOException("Permanent failure processing task " + task, 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.wave.server.googleimport;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileReadChannel;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
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.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import com.google.walkaround.proto.FetchAttachmentsAndImportWaveletTask;
import com.google.walkaround.proto.FetchAttachmentsAndImportWaveletTask.ImportedAttachmentInfo;
import com.google.walkaround.proto.FetchAttachmentsAndImportWaveletTask.RemoteAttachmentInfo;
import com.google.walkaround.proto.ImportTaskPayload;
import com.google.walkaround.proto.ImportWaveletTask;
import com.google.walkaround.proto.ImportWaveletTask.ImportedAttachment;
import com.google.walkaround.proto.gson.FetchAttachmentsAndImportWaveletTaskGsonImpl.ImportedAttachmentInfoGsonImpl;
import com.google.walkaround.proto.gson.ImportTaskPayloadGsonImpl;
import com.google.walkaround.proto.gson.ImportWaveletTaskGsonImpl.ImportedAttachmentGsonImpl;
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.shared.Assert;
import com.google.walkaround.wave.server.attachment.AttachmentId;
import com.google.walkaround.wave.server.attachment.RawAttachmentService;
import com.google.walkaround.wave.server.gxp.SourceInstance;
import org.waveprotocol.wave.model.id.WaveId;
import org.waveprotocol.wave.model.id.WaveletId;
import org.waveprotocol.wave.model.id.WaveletName;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Processes {@link FetchAttachmentsAndImportWaveletTask}s.
*
* @author ohler@google.com (Christian Ohler)
*/
public class FetchAttachmentsProcessor {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(FetchAttachmentsProcessor.class.getName());
private final SourceInstance.Factory sourceInstanceFactory;
private final RawAttachmentService rawAttachmentService;
private final URLFetchService urlfetch;
@Inject
public FetchAttachmentsProcessor(SourceInstance.Factory sourceInstanceFactory,
RawAttachmentService rawAttachmentService,
URLFetchService urlfetch) {
this.sourceInstanceFactory = sourceInstanceFactory;
this.rawAttachmentService = rawAttachmentService;
this.urlfetch = urlfetch;
}
private static final String DEFAULT_FILE_NAME = "attachment";
private static final int MAX_FETCHES_PER_TASK = 5;
private static final int MAX_FILE_BYTES_TRANSFERRED_PER_RPC = 972800;
private static final int BUFFER_BYTES = MAX_FILE_BYTES_TRANSFERRED_PER_RPC;
private static Object prettyBytes(final byte[] bytes, final int offset, final int length) {
return new Object() {
@Override public String toString() {
StringBuilder out = new StringBuilder("[");
for (int i = offset; i < length; i++) {
if (i != offset) {
out.append(" ");
}
out.append(String.format("%02x", bytes[i]));
}
return out + "]@" + String.format("%x", System.identityHashCode(bytes));
}
};
}
private static Object prettyBytes(byte[] bytes) {
return prettyBytes(bytes, 0, bytes.length);
}
private static FileService getFileService() {
return FileServiceFactory.getFileService();
}
private static AppEngineFile newBlob(@Nullable String mimeType, String downloadFilename)
throws IOException {
return getFileService().createNewBlobFile(mimeType, downloadFilename);
}
private static byte[] slurp(AppEngineFile file) throws IOException {
FileReadChannel in = getFileService().openReadChannel(file, false);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteBuffer buf = ByteBuffer.allocate(BUFFER_BYTES);
while (true) {
buf.clear();
int bytesRead = in.read(buf);
if (bytesRead < 0) {
break;
}
out.write(buf.array(), 0, bytesRead);
}
return out.toByteArray();
}
private static byte[] getBytes(ByteBuffer buf) {
byte[] bytes = new byte[buf.remaining()];
buf.get(bytes);
return bytes;
}
private static AppEngineFile dump(@Nullable String mimeType, String downloadFilename,
ByteBuffer bytes) throws IOException {
bytes.rewind();
AppEngineFile file = newBlob(mimeType, downloadFilename);
FileWriteChannel out = getFileService().openWriteChannel(file, true);
while (bytes.hasRemaining()) {
out.write(bytes);
}
out.closeFinally();
// Verify if what's in the file matches what we wanted to write -- the Files
// API is still experimental and I've seen it misbehave.
bytes.rewind();
byte[] expected = getBytes(bytes);
byte[] actual = slurp(file);
if (!Arrays.equals(expected, actual)) {
// These may be big log messages, but we need to log something that helps debugging.
log.warning("Tried to write: " + prettyBytes(expected));
log.warning("Bytes found in file: " + prettyBytes(actual));
throw new IOException("File " + file + " does not contain the bytes we intended to write");
}
return file;
}
@Nullable private AttachmentId fetchAttachment(
SourceInstance instance, RemoteAttachmentInfo info) {
final String url = instance.getFullAttachmentUrl(info.getPath());
final Long expectedBytes = info.hasSizeBytes() ? info.getSizeBytes() : null;
final String mimeType = info.hasMimeType() ? info.getMimeType() : null;
final String filename = info.hasFilename() ? info.getFilename() : DEFAULT_FILE_NAME;
try {
return new RetryHelper().run(
new RetryHelper.Body<AttachmentId>() {
@Override public AttachmentId run() throws RetryableFailure, PermanentFailure {
log.info("Fetching attachment " + url);
try {
// We could fetch several attachments asynchronously in parallel to save instance
// hours, but let's hope that the connection between App Engine and Google Wave
// is fast enough to make that irrelevant.
HTTPResponse response = urlfetch.fetch(
new HTTPRequest(new URL(url), HTTPMethod.GET));
if (response.getResponseCode() != 200) {
throw new RetryableFailure("Unexpected response code: "
+ response.getResponseCode());
}
byte[] bytes = response.getContent();
if (expectedBytes != null) {
Assert.check(expectedBytes == bytes.length, "Expected %s bytes, got %s: %s",
expectedBytes, bytes.length, prettyBytes(bytes));
}
final AppEngineFile file = dump(mimeType, filename, ByteBuffer.wrap(bytes));
log.info("Wrote file " + file);
BlobKey blobKey =
// NOTE(ohler): When running locally with unapplied jobs
// enabled, getBlobKey() sometimes returns null here even
// though it shouldn't, according to its documentation. So
// we retry. Not sure if this is needed when deployed.
new RetryHelper().run(
new RetryHelper.Body<BlobKey>() {
@Override public BlobKey run() throws RetryableFailure {
BlobKey key = getFileService().getBlobKey(file);
if (key != null) {
return key;
} else {
throw new RetryableFailure("getBlobKey(" + file + ") returned null");
}
}
});
return rawAttachmentService.turnBlobIntoAttachment(blobKey);
} catch (IOException e) {
throw new RetryableFailure("IOException fetching " + url);
}
}
});
} catch (PermanentFailure e) {
log.severe("Failed to fetch attachment " + url + ", skipping");
return null;
}
}
public List<ImportTaskPayload> fetchAttachments(FetchAttachmentsAndImportWaveletTask task)
throws PermanentFailure {
ImportWaveletTask waveletTask = task.getOriginalImportTask();
SourceInstance instance = sourceInstanceFactory.parseUnchecked(waveletTask.getInstance());
WaveletName waveletName = WaveletName.of(
WaveId.deserialise(waveletTask.getWaveId()),
WaveletId.deserialise(waveletTask.getWaveletId()));
LinkedList<RemoteAttachmentInfo> toImport = Lists.newLinkedList(task.getToImport());
int infosFetchedThisTask = 0;
while (!toImport.isEmpty() && infosFetchedThisTask < MAX_FETCHES_PER_TASK) {
RemoteAttachmentInfo info = toImport.removeFirst();
AttachmentId localId = fetchAttachment(instance, info);
log.info("Local id: " + localId);
ImportedAttachmentInfo imported = new ImportedAttachmentInfoGsonImpl();
imported.setRemoteInfo(info);
if (localId != null) {
imported.setLocalId(localId.getId());
}
infosFetchedThisTask++;
task.addImported(imported);
}
if (toImport.isEmpty()) {
log.info("All attachments imported, will import wavelet");
for (ImportedAttachmentInfo info : task.getImported()) {
ImportedAttachment attachment = new ImportedAttachmentGsonImpl();
attachment.setRemoteId(info.getRemoteInfo().getRemoteId());
if (info.hasLocalId()) {
attachment.setLocalId(info.getLocalId());
}
waveletTask.addAttachment(attachment);
}
ImportTaskPayload payload = new ImportTaskPayloadGsonImpl();
payload.setImportWaveletTask(waveletTask);
return ImmutableList.of(payload);
} else {
log.info("Will fetch remaining attachments in new task");
task.clearToImport();
task.addAllToImport(toImport);
ImportTaskPayload payload = new ImportTaskPayloadGsonImpl();
payload.setFetchAttachmentsTask(task);
return ImmutableList.of(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.wave.server.googleimport;
import com.google.appengine.api.taskqueue.Queue;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.walkaround.proto.ImportTaskPayload;
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.AbstractHandler;
import com.google.walkaround.util.server.servlet.BadRequestException;
import com.google.walkaround.util.server.servlet.TryAgainLaterException;
import com.google.walkaround.wave.server.auth.AccountStore;
import com.google.walkaround.wave.server.auth.ServletAuthHelper;
import com.google.walkaround.wave.server.auth.StableUserId;
import com.google.walkaround.wave.server.auth.UserContext;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Handles task queue callbacks for import tasks.
*
* @author ohler@google.com (Christian Ohler)
*/
public class ImportTaskHandler extends AbstractHandler {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(ImportTaskHandler.class.getName());
public static final String USER_ID_HEADER = "X-Walkaround-Import-User-Id";
public static final String TASK_ID_HEADER = "X-Walkaround-Import-Task-Id";
@Inject AccountStore accountStore;
@Inject UserContext userContext;
@Inject ServletAuthHelper authHelper;
@Inject PerUserTable perUserTable;
@Inject CheckedDatastore datastore;
@Inject @ImportTaskQueue Queue taskQueue;
// Provider because we need to set up the UserContext before this can be instantiated.
@Inject Provider<TaskDispatcher> taskDispatcher;
private ImportTask readTask(StableUserId userId, long taskId) throws IOException {
try {
CheckedTransaction tx = datastore.beginTransaction();
try {
return perUserTable.getTask(tx, userId, taskId);
} finally {
tx.rollback();
}
} catch (RetryableFailure e) {
// If we can't even read the task, let the task queue retry rather than
// doing it here. Seems better because it means we don't use waste a
// thread for waiting.
throw new IOException("PermanentFailure reading task: " + userId + ", " + taskId, e);
} catch (PermanentFailure e) {
throw new IOException("PermanentFailure reading task: " + userId + ", " + taskId, e);
}
}
private void handleTask(final StableUserId userId, final long taskId) throws IOException {
ImportTask taskToProcess = readTask(userId, taskId);
if (taskToProcess == null) {
log.info("Task is gone from datastore; either already completed or cancelled");
return;
}
log.info("Task to process: " + taskToProcess);
final List<ImportTaskPayload> followupTasks = taskDispatcher.get().processTask(taskToProcess);
// If the processing returns normally, the task has been completed. (Other
// tasks may have been scheduled.)
try {
new RetryHelper().run(
new RetryHelper.VoidBody() {
@Override public void run() throws RetryableFailure, PermanentFailure {
CheckedTransaction tx = datastore.beginTransaction();
try {
if (perUserTable.getTask(tx, userId, taskId) == null) {
// If the task is already gone, make sure we don't schedule follow-up tasks.
log.info(
"Task is gone from datastore; either completed concurrently or cancelled");
return;
}
perUserTable.deleteTask(tx, userId, taskId);
for (ImportTaskPayload payload : followupTasks) {
perUserTable.addTask(tx, userId, payload);
}
tx.commit();
} finally {
tx.close();
}
}
});
} catch (PermanentFailure e) {
// Ugh, all the real work is done but then we failed to delete the task
// entity. We'll have to do the task all over again...
throw new IOException("PermanentFailure deleting completed task: " + userId + " " + taskId,
e);
}
}
@Override
public void doPost(final HttpServletRequest req, final HttpServletResponse resp)
throws IOException, ServletException {
log.info("Received task: queue " + req.getHeader("X-AppEngine-QueueName")
+ ", task name " + req.getHeader("X-AppEngine-TaskName")
+ ", retry count " + req.getHeader("X-AppEngine-TaskRetryCount"));
final StableUserId userId = new StableUserId(requireParameter(req, USER_ID_HEADER));
final long taskId;
try {
taskId = Long.parseLong(requireParameter(req, TASK_ID_HEADER));
} catch (NumberFormatException e) {
throw new BadRequestException("Bad task id");
}
log.info("userId=" + userId + ", taskId=" + taskId);
authHelper.serve(
new ServletAuthHelper.ServletBody() {
@Override public void run() throws IOException {
handleTask(userId, taskId);
}
},
new ServletAuthHelper.AccountLookup() {
@Override @Nullable public AccountStore.Record getAccount()
throws PermanentFailure, IOException {
return accountStore.get(userId);
}
},
new ServletAuthHelper.NeedNewOAuthTokenHandler() {
@Override public void sendNeedTokenResponse() throws IOException {
// TODO(ohler): When loading /import (and probably /inbox as well),
// check not just whether we have an OAuth token, but also whether
// it's still valid.
throw new TryAgainLaterException(
"Need OAuth token. Let's hope the user re-enables interactively: "
+ userId);
}
});
}
}
| 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.server.googleimport;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Objects;
import com.google.walkaround.proto.RobotSearchDigest;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.wave.server.gxp.SourceInstance;
import org.waveprotocol.wave.model.id.WaveletId;
import javax.annotation.Nullable;
/**
* Identifies a wave on a remote instance.
*
* @author ohler@google.com (Christian Ohler)
*/
public class RemoteConvWavelet {
private final SourceInstance sourceInstance;
private final RobotSearchDigest digest;
// WaveId is in the digest.
private final WaveletId waveletId;
@Nullable private SlobId privateLocalId;
@Nullable private SlobId sharedLocalId;
public RemoteConvWavelet(SourceInstance sourceInstance,
RobotSearchDigest digest,
WaveletId waveletId,
@Nullable SlobId privateLocalId,
@Nullable SlobId sharedLocalId) {
this.sourceInstance = checkNotNull(sourceInstance, "Null sourceInstance");
this.digest = checkNotNull(digest, "Null digest");
this.waveletId = checkNotNull(waveletId, "Null waveletId");
this.privateLocalId = privateLocalId;
this.sharedLocalId = sharedLocalId;
}
public SourceInstance getSourceInstance() {
return sourceInstance;
}
public RobotSearchDigest getDigest() {
return digest;
}
public WaveletId getWaveletId() {
return waveletId;
}
@Nullable public SlobId getPrivateLocalId() {
return privateLocalId;
}
public RemoteConvWavelet setPrivateLocalId(@Nullable SlobId privateLocalId) {
this.privateLocalId = privateLocalId;
return this;
}
@Nullable public SlobId getSharedLocalId() {
return sharedLocalId;
}
public RemoteConvWavelet setSharedLocalId(@Nullable SlobId sharedLocalId) {
this.sharedLocalId = sharedLocalId;
return this;
}
@Override public String toString() {
return getClass().getSimpleName() + "("
+ sourceInstance + ", "
+ digest + ", "
+ waveletId + ", "
+ privateLocalId + ", "
+ sharedLocalId
+ ")";
}
@Override public final boolean equals(Object o) {
if (o == this) { return true; }
if (!(o instanceof RemoteConvWavelet)) { return false; }
RemoteConvWavelet other = (RemoteConvWavelet) o;
return Objects.equal(sourceInstance, other.sourceInstance)
&& Objects.equal(digest, other.digest)
&& Objects.equal(waveletId, other.waveletId)
&& Objects.equal(privateLocalId, other.privateLocalId)
&& Objects.equal(sharedLocalId, other.sharedLocalId);
}
@Override public final int hashCode() {
return Objects.hashCode(sourceInstance, digest, waveletId, privateLocalId, sharedLocalId);
}
}
| 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.server.googleimport;
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.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import com.google.walkaround.proto.GoogleImport.GoogleDocument;
import com.google.walkaround.proto.GoogleImport.GoogleWavelet;
import com.google.walkaround.proto.RobotSearchDigest;
import com.google.walkaround.proto.gson.RobotSearchDigestGsonImpl;
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.wave.server.auth.OAuthedFetchService;
import com.google.walkaround.wave.server.auth.OAuthedFetchService.TokenRefreshNeededDetector;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.waveprotocol.wave.federation.Proto.ProtocolAppliedWaveletDelta;
import org.waveprotocol.wave.model.id.WaveId;
import org.waveprotocol.wave.model.id.WaveletId;
import org.waveprotocol.wave.model.id.WaveletName;
import org.waveprotocol.wave.model.util.Pair;
import org.waveprotocol.wave.model.util.ValueUtils;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
/**
* Simple interface to Google Wave's active robot API.
*
* We don't use the "official" Wave robot API library since it doesn't support
* some of the APIs that we need (raw snapshot/delta export), and implementing
* what we need is easy anyway. The main difficulty is OAuth, but we already
* have code for that.
*
* @author ohler@google.com (Christian Ohler)
*/
public class RobotApi {
public interface Factory {
RobotApi create(String baseUrl);
}
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(RobotApi.class.getName());
private final OAuthedFetchService fetch;
private final String baseUrl;
@Inject
public RobotApi(OAuthedFetchService fetch,
@Assisted String baseUrl) {
this.fetch = fetch;
this.baseUrl = baseUrl;
}
private static final String OP_ID = "op_id";
private static final String ROBOT_API_METHOD_FETCH_WAVE = "wave.robot.fetchWave";
private static final String ROBOT_API_METHOD_SEARCH = "wave.robot.search";
private static final String EXPECTED_CONTENT_TYPE = "application/json; charset=UTF-8";
private final TokenRefreshNeededDetector robotErrorCode401Detector =
new TokenRefreshNeededDetector() {
@Override public boolean refreshNeeded(HTTPResponse resp) throws IOException {
if (resp.getResponseCode() == 401) {
log.warning("Response code 401: " + resp);
return true;
}
if (!EXPECTED_CONTENT_TYPE.equals(fetch.getSingleHeader(resp, "Content-Type"))) {
return false;
}
JSONObject result = parseJsonResponseBody(resp);
try {
if (result.has("error")) {
JSONObject error = result.getJSONObject("error");
if (error.has("code") && error.getInt("code") == 401) {
log.warning("Looks like a 401: " + result + ", " + resp);
return true;
} else {
return false;
}
} else {
return false;
}
} catch (JSONException e) {
throw new RuntimeException("JSONException parsing response: " + result, e);
}
}
};
// Example of the kind of search request body that we send:
// [{"id":"op_id",
// "method":"wave.robot.search",
// "params":
// {"query":"abc",
// "index":0,
// "numResults":100
// }
// }
// ]
//
// Example of the kind of response body that we receive:
// [{"id":"op_id",
// "data":
// {"searchResults":
// {"query":"abc",
// "numResults":1,
// "digests":
// [{"waveId":"googlewave.com!w+aaaa",
// "title":"aaaa",
// "participants":
// ["aaaa@googlewave.com",
// "aaab@googlewave.com",
// "aaaa@googlegroups.com"
// ],
// "lastModified":1111111111111,
// "snippet":"aaaa",
// "blipCount":2,
// "unreadCount":1
// }
// ]
// }
// }
// }
// ]
private JSONObject parseJsonResponseBody(HTTPResponse resp) throws IOException {
// The response looks like this:
// [{"id":"op_id", "data":X}]
// We return the single item in this array.
String body = fetch.getUtf8ResponseBody(resp, EXPECTED_CONTENT_TYPE);
try {
JSONArray items = new JSONArray(body);
if (items.length() != 1) {
throw new RuntimeException("Unexpected length: " + items.length() + ": " + items);
}
JSONObject item = items.getJSONObject(0);
if (!OP_ID.equals(item.getString("id"))) {
throw new RuntimeException("Unexpected id: " + item);
}
return item;
} catch (JSONException e) {
throw new RuntimeException("JSONException parsing response: " + body, e);
}
}
private JSONObject callRobotApi(final String method, Map<String, Object> params)
throws IOException {
JSONArray ops = new JSONArray();
try {
JSONObject jsonParams = new JSONObject();
for (Map.Entry<String, Object> e : params.entrySet()) {
jsonParams.put(e.getKey(), e.getValue());
}
JSONObject op = new JSONObject();
op.put("params", jsonParams);
op.put("method", method);
op.put("id", OP_ID);
ops.put(op);
} catch (JSONException e) {
throw new RuntimeException("Failed to construct JSON object", e);
}
final HTTPRequest req = new HTTPRequest(new URL(baseUrl), HTTPMethod.POST,
FetchOptions.Builder.disallowTruncate().followRedirects()
.validateCertificate().setDeadline(20.0));
log.info("payload=" + ops);
req.setHeader(new HTTPHeader("Content-Type", "application/json; charset=UTF-8"));
req.setPayload(ops.toString().getBytes(Charsets.UTF_8));
try {
return new RetryHelper().run(new RetryHelper.Body<JSONObject>() {
@Override public JSONObject run() throws RetryableFailure, PermanentFailure {
JSONObject result;
try {
result = parseJsonResponseBody(fetch.fetch(req, robotErrorCode401Detector));
} catch (IOException e) {
throw new PermanentFailure("IOException with " + method + ": " + req, e);
}
log.info("result=" + ValueUtils.abbrev("" + result, 500));
try {
if (result.has("error")) {
log.warning("Error result: " + result);
JSONObject error = result.getJSONObject("error");
throw new RuntimeException("Error from robot API: " + error);
} else if (result.has("data")) {
JSONObject data = result.getJSONObject("data");
if (data.length() == 0) {
// Apparently, the server often sends {"id":"op_id", "data":{}} when
// something went wrong on the server side, so we translate that to an
// IOException.
throw new RetryableFailure("Robot API response looks like an error: " + result);
} else {
return data;
}
} else {
throw new RuntimeException("Result has neither error nor data: " + result);
}
} catch (JSONException e) {
throw new RuntimeException("JSONException parsing result: " + result, e);
}
}
});
} catch (PermanentFailure e) {
throw new IOException("PermanentFailure with " + method + ": " + req);
}
}
private Map<String, Object> getFetchWaveParamMap(WaveletName waveletName, Object... extraParams) {
Preconditions.checkArgument(extraParams.length % 2 == 0,
"extraParams must come in pairs: %s", extraParams);
ImmutableMap.Builder<String, Object> b = ImmutableMap.builder();
b.put("waveId", waveletName.waveId.serialise());
b.put("waveletId", waveletName.waveletId.serialise());
for (int i = 0; i < extraParams.length; i += 2) {
b.put((String) extraParams[i], extraParams[i + 1]);
}
return b.build();
}
/**
* Gets the current state of the wavelet.
*/
public Pair<GoogleWavelet, ImmutableList<GoogleDocument>> getSnapshot(WaveletName waveletName)
throws IOException {
JSONObject resp = callRobotApi(ROBOT_API_METHOD_FETCH_WAVE,
getFetchWaveParamMap(waveletName, "returnRawSnapshot", true));
try {
JSONArray snapshot = resp.getJSONArray("rawSnapshot");
// NOTE(ohler): snapshot array is not of a uniform type: element 0 is the
// wavelet metadata, the remaining elements are documents.
GoogleWavelet wavelet = GoogleWavelet.parseFrom(Base64.decodeBase64(snapshot.getString(0)));
ImmutableList.Builder<GoogleDocument> documents = ImmutableList.builder();
for (int i = 1; i < snapshot.length(); i++) {
documents.add(GoogleDocument.parseFrom(Base64.decodeBase64(snapshot.getString(i))));
}
return Pair.of(wavelet, documents.build());
} catch (JSONException e) {
throw new RuntimeException("Failed to parse snapshot response: " + resp, e);
}
}
/**
* Gets delta history for the wavelet. The server limits its response size in
* various ways but always return at least one delta; this method has the same
* behavior.
*/
public List<ProtocolAppliedWaveletDelta> getRawDeltas(WaveletName waveletName, long fromVersion)
throws IOException {
JSONObject resp = callRobotApi(ROBOT_API_METHOD_FETCH_WAVE,
getFetchWaveParamMap(waveletName, "rawDeltasFromVersion", fromVersion));
try {
JSONArray deltas = resp.getJSONArray("rawDeltas");
ImmutableList.Builder<ProtocolAppliedWaveletDelta> out = ImmutableList.builder();
for (int i = 0; i < deltas.length(); i++) {
out.add(ProtocolAppliedWaveletDelta.parseFrom(Base64.decodeBase64(deltas.getString(i))));
}
return out.build();
} catch (JSONException e) {
throw new RuntimeException("Failed to parse deltas response: " + resp, e);
}
}
/**
* Gets the list of wavelets in a wave that are visible the user.
*/
public List<WaveletId> getWaveView(WaveId waveId) throws IOException {
JSONObject resp = callRobotApi(ROBOT_API_METHOD_FETCH_WAVE,
ImmutableMap.<String, Object>of("waveId", waveId.serialise(), "listWavelets", true));
try {
JSONArray ids = resp.getJSONArray("waveletIds");
ImmutableList.Builder<WaveletId> out = ImmutableList.builder();
for (int i = 0; i < ids.length(); i++) {
out.add(WaveletId.deserialise(ids.getString(i)));
}
List<WaveletId> view = out.build();
log.info("getWaveView(" + waveId + ") = " + view);
return view;
} catch (JSONException e) {
throw new RuntimeException("Failed to parse listWavelets response: " + resp, e);
}
}
/**
* Searches the user's waves. Returns at most {@code maxResults} results,
* starting with the {@code startIndex}-th result (0-based index).
*
* Note: Google Wave's search feature may limit the overall set of result for
* any given query to the first N hits (for some N, perhaps 300), regardless
* of {@code startIndex} and {@code maxResults}, so don't rely on these to
* iterate over all waves.
*/
public List<RobotSearchDigest> search(String query, int startIndex, int maxResults)
throws IOException {
log.info("search(" + query + ", " + startIndex + ", " + maxResults + ")");
JSONObject response = callRobotApi(ROBOT_API_METHOD_SEARCH,
ImmutableMap.<String, Object>of("query", query,
"index", startIndex,
"numResults", maxResults));
// The response looks like this:
// {"searchResults":
// {"query":"after:2008/01/01 before:2010/01/01",
// "numResults":1,
// "digests":
// [{"waveId":"googlewave.com!w+aaaa",
// "title":"aaaa",
// "participants":
// ["aaaa@googlewave.com",
// "aaab@googlewave.com",
// "aaaa@googlegroups.com"
// ],
// "lastModified":1111111111111,
// "snippet":"aaaa"
// "blipCount":2,
// "unreadCount":1,
// }
// ]
// }
// }
ImmutableList.Builder<RobotSearchDigest> digests = ImmutableList.builder();
try {
JSONObject results = response.getJSONObject("searchResults");
try {
if (results.getInt("numResults") != results.getJSONArray("digests").length()) {
throw new RuntimeException("Mismatched numResults and digests array length: "
+ results.getInt("numResults") + " vs. " + results.getJSONArray("digests"));
}
JSONArray rawDigests = results.getJSONArray("digests");
for (int i = 0; i < rawDigests.length(); i++) {
JSONObject rawDigest = rawDigests.getJSONObject(i);
try {
RobotSearchDigest digest = new RobotSearchDigestGsonImpl();
digest.setWaveId(WaveId.deserialise(rawDigest.getString("waveId")).serialise());
JSONArray rawParticipants = rawDigest.getJSONArray("participants");
for (int j = 0; j < rawParticipants.length(); j++) {
digest.addParticipant(rawParticipants.getString(j));
}
digest.setTitle(rawDigest.getString("title"));
digest.setSnippet(rawDigest.getString("snippet"));
digest.setLastModifiedMillis(rawDigest.getLong("lastModified"));
digest.setBlipCount(rawDigest.getInt("blipCount"));
digest.setUnreadBlipCount(rawDigest.getInt("unreadCount"));
digests.add(digest);
} catch (JSONException e) {
throw new RuntimeException("Failed to parse search digest: " + rawDigest, e);
}
}
} catch (JSONException e) {
throw new RuntimeException("Failed to parse search results: " + results, e);
}
} catch (JSONException e) {
throw new RuntimeException("Failed to parse search response: " + response, e);
}
return digests.build();
}
}
| 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.server.googleimport;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.walkaround.proto.ImportTaskPayload;
import com.google.walkaround.wave.server.auth.StableUserId;
/**
* Represents a task that is part of the import process for a user.
*
* @author ohler@google.com (Christian Ohler)
*/
public class ImportTask {
private final StableUserId userId;
private final long taskId;
private final long creationTimeMillis;
private final ImportTaskPayload payload;
public ImportTask(StableUserId userId,
long taskId,
long creationTimeMillis,
ImportTaskPayload payload) {
Preconditions.checkNotNull(userId, "Null userId");
Preconditions.checkNotNull(payload, "Null payload");
this.userId = userId;
this.taskId = taskId;
this.creationTimeMillis = creationTimeMillis;
this.payload = payload;
}
public StableUserId getUserId() {
return userId;
}
public long getTaskId() {
return taskId;
}
public long getCreationTimeMillis() {
return creationTimeMillis;
}
public ImportTaskPayload getPayload() {
return payload;
}
@Override public String toString() {
return "ImportTask("
+ userId + ", "
+ taskId + ", "
+ creationTimeMillis + ", "
+ payload
+ ")";
}
@Override public final boolean equals(Object o) {
if (o == this) { return true; }
if (!(o instanceof ImportTask)) { return false; }
ImportTask other = (ImportTask) o;
return taskId == other.taskId
&& creationTimeMillis == other.creationTimeMillis
&& Objects.equal(userId, other.userId)
&& Objects.equal(payload, other.payload);
}
@Override public final int hashCode() {
return Objects.hashCode(userId, taskId, creationTimeMillis, 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.wave.server.googleimport;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.inject.Inject;
import com.google.walkaround.proto.ConvMetadata;
import com.google.walkaround.proto.FetchAttachmentsAndImportWaveletTask;
import com.google.walkaround.proto.FetchAttachmentsAndImportWaveletTask.RemoteAttachmentInfo;
import com.google.walkaround.proto.GoogleImport.GoogleDocument;
import com.google.walkaround.proto.GoogleImport.GoogleDocumentContent;
import com.google.walkaround.proto.GoogleImport.GoogleDocumentContent.Component;
import com.google.walkaround.proto.GoogleImport.GoogleDocumentContent.ElementStart;
import com.google.walkaround.proto.GoogleImport.GoogleDocumentContent.KeyValuePair;
import com.google.walkaround.proto.GoogleImport.GoogleWavelet;
import com.google.walkaround.proto.ImportMetadata;
import com.google.walkaround.proto.ImportSettings;
import com.google.walkaround.proto.ImportTaskPayload;
import com.google.walkaround.proto.ImportWaveletTask;
import com.google.walkaround.proto.ImportWaveletTask.ImportedAttachment;
import com.google.walkaround.proto.gson.ConvMetadataGsonImpl;
import com.google.walkaround.proto.gson.FetchAttachmentsAndImportWaveletTaskGsonImpl;
import com.google.walkaround.proto.gson.FetchAttachmentsAndImportWaveletTaskGsonImpl.RemoteAttachmentInfoGsonImpl;
import com.google.walkaround.proto.gson.ImportMetadataGsonImpl;
import com.google.walkaround.proto.gson.ImportTaskPayloadGsonImpl;
import com.google.walkaround.slob.server.MutationLog;
import com.google.walkaround.slob.server.SlobFacilities;
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.StateAndVersion;
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.shared.Assert;
import com.google.walkaround.wave.server.WaveletCreator;
import com.google.walkaround.wave.server.attachment.AttachmentId;
import com.google.walkaround.wave.server.auth.StableUserId;
import com.google.walkaround.wave.server.conv.ConvMetadataStore;
import com.google.walkaround.wave.server.conv.ConvStore;
import com.google.walkaround.wave.server.googleimport.conversion.AttachmentIdConverter;
import com.google.walkaround.wave.server.googleimport.conversion.HistorySynthesizer;
import com.google.walkaround.wave.server.googleimport.conversion.PrivateReplyAnchorLegacyIdConverter;
import com.google.walkaround.wave.server.googleimport.conversion.StripWColonFilter;
import com.google.walkaround.wave.server.googleimport.conversion.WaveletHistoryConverter;
import com.google.walkaround.wave.server.gxp.SourceInstance;
import com.google.walkaround.wave.server.model.ServerMessageSerializer;
import com.google.walkaround.wave.server.model.WaveObjectStoreModel.ReadableWaveletObject;
import com.google.walkaround.wave.shared.WaveSerializer;
import org.waveprotocol.box.server.common.CoreWaveletOperationSerializer;
import org.waveprotocol.wave.federation.Proto.ProtocolAppliedWaveletDelta;
import org.waveprotocol.wave.federation.Proto.ProtocolWaveletDelta;
import org.waveprotocol.wave.migration.helpers.FixLinkAnnotationsFilter;
import org.waveprotocol.wave.model.document.operation.Nindo;
import org.waveprotocol.wave.model.id.IdConstants;
import org.waveprotocol.wave.model.id.IdUtil;
import org.waveprotocol.wave.model.id.WaveId;
import org.waveprotocol.wave.model.id.WaveletId;
import org.waveprotocol.wave.model.id.WaveletName;
import org.waveprotocol.wave.model.operation.wave.AddParticipant;
import org.waveprotocol.wave.model.operation.wave.NoOp;
import org.waveprotocol.wave.model.operation.wave.RemoveParticipant;
import org.waveprotocol.wave.model.operation.wave.VersionUpdateOp;
import org.waveprotocol.wave.model.operation.wave.WaveletBlipOperation;
import org.waveprotocol.wave.model.operation.wave.WaveletDelta;
import org.waveprotocol.wave.model.operation.wave.WaveletOperation;
import org.waveprotocol.wave.model.operation.wave.WaveletOperationContext;
import org.waveprotocol.wave.model.operation.wave.WaveletOperationVisitor;
import org.waveprotocol.wave.model.util.Pair;
import org.waveprotocol.wave.model.wave.ParticipantId;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Processes {@link ImportWaveletTask}s.
*
* @author ohler@google.com (Christian Ohler)
*/
public class ImportWaveletProcessor {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(ImportWaveletProcessor.class.getName());
private static final WaveSerializer SERIALIZER =
new WaveSerializer(new ServerMessageSerializer());
private final RobotApi.Factory robotApiFactory;
private final SourceInstance.Factory sourceInstanceFactory;
private final WaveletCreator waveletCreator;
private final ParticipantId importingUser;
private final StableUserId userId;
private final PerUserTable perUserTable;
private final SharedImportTable sharedImportTable;
private final CheckedDatastore datastore;
private final SlobFacilities convSlobFacilities;
private final ConvMetadataStore convMetadataStore;
@Inject
public ImportWaveletProcessor(RobotApi.Factory robotApiFactory,
SourceInstance.Factory sourceInstanceFactory,
WaveletCreator waveletCreator,
ParticipantId importingUser,
StableUserId userId,
PerUserTable perUserTable,
SharedImportTable sharedImportTable,
CheckedDatastore datastore,
@ConvStore SlobFacilities slobFacilities,
ConvMetadataStore convMetadataStore) {
this.robotApiFactory = robotApiFactory;
this.sourceInstanceFactory = sourceInstanceFactory;
this.waveletCreator = waveletCreator;
this.importingUser = importingUser;
this.userId = userId;
this.perUserTable = perUserTable;
this.sharedImportTable = sharedImportTable;
this.datastore = datastore;
this.convSlobFacilities = slobFacilities;
this.convMetadataStore = convMetadataStore;
}
/** Returns a nindo converter for conversational wavelets. */
private Function<Pair<String, Nindo>, Nindo> getConvNindoConverter(
final Map<String, AttachmentId> attachmentIdMapping) {
return new Function<Pair<String, Nindo>, Nindo>() {
@Override public Nindo apply(Pair<String, Nindo> in) {
String documentId = in.getFirst();
Nindo.Builder out = new Nindo.Builder();
in.getSecond().apply(
// StripWColonFilter must be before AttachmentIdConverter.
new StripWColonFilter(
new FixLinkAnnotationsFilter(
new PrivateReplyAnchorLegacyIdConverter(documentId,
new AttachmentIdConverter(attachmentIdMapping,
out)))));
return out.build();
}
};
}
private String convertGooglewaveToGmail(String participantId) {
return participantId.replace("@googlewave.com", "@gmail.com");
}
private ParticipantId convertGooglewaveToGmail(ParticipantId participantId) {
return ParticipantId.ofUnsafe(convertGooglewaveToGmail(participantId.getAddress()));
}
private Pair<GoogleWavelet, ImmutableList<GoogleDocument>> convertGooglewaveToGmail(
Pair<GoogleWavelet, ? extends List<GoogleDocument>> pair) {
GoogleWavelet w = pair.getFirst();
List<GoogleDocument> docs = pair.getSecond();
GoogleWavelet.Builder w2 = GoogleWavelet.newBuilder(w);
w2.setCreator(convertGooglewaveToGmail(w.getCreator()));
w2.clearParticipant();
for (String p : w.getParticipantList()) {
w2.addParticipant(convertGooglewaveToGmail(p));
}
ImmutableList.Builder<GoogleDocument> docs2 = ImmutableList.builder();
for (GoogleDocument doc : docs) {
GoogleDocument.Builder doc2 = GoogleDocument.newBuilder(doc);
doc2.setAuthor(convertGooglewaveToGmail(doc.getAuthor()));
doc2.clearContributor();
for (String p : doc.getContributorList()) {
doc2.addContributor(convertGooglewaveToGmail(p));
}
docs2.add(doc2.build());
}
return Pair.of(w2.build(), docs2.build());
}
private WaveletOperation convertGooglewaveToGmail(final WaveletOperation op) {
final WaveletOperationContext newContext = new WaveletOperationContext(
convertGooglewaveToGmail(op.getContext().getCreator()),
op.getContext().getTimestamp(), op.getContext().getVersionIncrement(),
op.getContext().getHashedVersion());
final WaveletOperation[] result = { null };
op.acceptVisitor(new WaveletOperationVisitor() {
void setResult(WaveletOperation x) {
Preconditions.checkState(result[0] == null,
"%s: More than one result: %s, %s", op, result[0], x);
result[0] = x;
}
@Override public void visitNoOp(NoOp op) {
setResult(new NoOp(newContext));
}
@Override public void visitVersionUpdateOp(VersionUpdateOp op) {
throw new AssertionError("Unexpected visitVersionUpdateOp(" + op + ")");
}
@Override public void visitAddParticipant(AddParticipant op) {
setResult(
new AddParticipant(newContext, convertGooglewaveToGmail(op.getParticipantId())));
}
@Override public void visitRemoveParticipant(RemoveParticipant op) {
setResult(
new RemoveParticipant(newContext, convertGooglewaveToGmail(op.getParticipantId())));
}
@Override public void visitWaveletBlipOperation(WaveletBlipOperation waveletOp) {
setResult(WaveletOperation.cloneOp(waveletOp, newContext));
}
});
Assert.check(result[0] != null, "No result: %s", op);
return result[0];
}
private Map<String, AttachmentId> buildAttachmentMapping(ImportWaveletTask task) {
ImmutableMap.Builder<String, AttachmentId> out = ImmutableMap.builder();
for (ImportedAttachment attachment : task.getAttachment()) {
if (attachment.hasLocalId()) {
out.put(attachment.getRemoteId(), new AttachmentId(attachment.getLocalId()));
}
}
return out.build();
}
// Example attachment metadata document:
// document id: attach+foo
// begin doc
// <node key="upload_progress" value="678"></node>
// <node key="attachment_size" value="678"></node>
// <node key="mime_type" value="application/octet-stream"></node>
// <node key="filename" value="the-file-name"></node>
// <node key="attachment_url" value="/attachment/the-file-name?id=a-short-id&key=a-long-key"></node>
// end doc
private Map<String, String> makeMapFromDocument(GoogleDocumentContent doc,
String elementType, String keyAttributeName, String valueAttributeName) {
Preconditions.checkNotNull(elementType, "Null elementType");
Preconditions.checkNotNull(keyAttributeName, "Null keyAttributeName");
Preconditions.checkNotNull(valueAttributeName, "Null valueAttributeName");
Map<String, String> out = Maps.newHashMap();
for (Component component : doc.getComponentList()) {
if (component.hasElementStart()) {
ElementStart start = component.getElementStart();
Assert.check(elementType.equals(start.getType()), "Unexpected element type: %s", doc);
Map<String, String> attrs = Maps.newHashMap();
for (KeyValuePair attr : start.getAttributeList()) {
attrs.put(attr.getKey(), attr.getValue());
}
Assert.check(attrs.size() == 2, "Need two attrs: %s", doc);
String key = attrs.get(keyAttributeName);
String value = attrs.get(valueAttributeName);
Assert.check(key != null, "Key not found: %s", doc);
Assert.check(value != null, "Value not found: %s", doc);
// If already exists, overwrite. Last entry wins. TODO(ohler): confirm that this is
// consistent with how the documents are interpreted by Google Wave.
out.put(key, value);
}
}
return out;
}
private void populateAttachmentInfo(FetchAttachmentsAndImportWaveletTask newTask,
List<GoogleDocument> documentList, Map<String, GoogleDocument> attachmentDocs) {
for (Map.Entry<String, GoogleDocument> entry : attachmentDocs.entrySet()) {
String attachmentId = entry.getKey();
GoogleDocumentContent metadataDoc = entry.getValue().getContent();
log.info("metadataDoc=" + metadataDoc);
Map<String, String> map = makeMapFromDocument(metadataDoc, "node", "key", "value");
log.info("Attachment metadata for " + attachmentId + ": " + map + ")");
RemoteAttachmentInfo info = new RemoteAttachmentInfoGsonImpl();
info.setRemoteId(attachmentId);
if (map.get("attachment_url") == null) {
log.warning("Attachment " + attachmentId + " has no URL (incomplete upload?), skipping: "
+ map);
continue;
}
info.setPath(map.get("attachment_url"));
if (map.get("filename") != null) {
info.setFilename(map.get("filename"));
}
if (map.get("mime_type") != null) {
info.setMimeType(map.get("mime_type"));
}
if (map.get("size") != null) {
info.setSizeBytes(Long.parseLong(map.get("size")));
}
newTask.addToImport(info);
}
}
private Map<String, GoogleDocument> getAttachmentDocs(List<GoogleDocument> docs) {
Map<String, GoogleDocument> out = Maps.newHashMap();
for (GoogleDocument doc : docs) {
String docId = doc.getDocumentId();
Assert.check(!out.containsKey(docId), "Duplicate doc id %s: %s", docId, docs);
if (IdUtil.isAttachmentDataDocument(docId)) {
String[] components = IdUtil.split(docId);
if (components == null) {
throw new RuntimeException("Failed to split attachment doc id: " + docId);
}
if (components.length != 2) {
throw new RuntimeException("Bad number of components in attachment doc id " + docId
+ ": " + Arrays.toString(components));
}
if (!IdConstants.ATTACHMENT_METADATA_PREFIX.equals(components[0])) {
throw new RuntimeException("Bad first component in attachment doc id " + docId
+ ": " + Arrays.toString(components));
}
String attachmentId = components[1];
out.put(attachmentId, doc);
}
}
return ImmutableMap.copyOf(out);
}
private static class TaskCompleted extends Exception {
private static final long serialVersionUID = 623496132804869626L;
private final List<ImportTaskPayload> followupTasks;
public TaskCompleted(List<ImportTaskPayload> followupTasks) {
this.followupTasks = ImmutableList.copyOf(followupTasks);
}
public static TaskCompleted noFollowup() {
return new TaskCompleted(ImmutableList.<ImportTaskPayload>of());
}
public static TaskCompleted withFollowup(ImportTaskPayload... followupTasks) {
return new TaskCompleted(ImmutableList.copyOf(followupTasks));
}
public static TaskCompleted withFollowup(ImportWaveletTask followupTask) {
ImportTaskPayload payload = new ImportTaskPayloadGsonImpl();
payload.setImportWaveletTask(followupTask);
return TaskCompleted.withFollowup(payload);
}
}
private class ImportContext {
private final ImportWaveletTask task;
private final SourceInstance instance;
private final WaveletName waveletName;
private final RobotApi robotApi;
private ImportContext(ImportWaveletTask task,
SourceInstance instance,
WaveletName waveletName,
RobotApi robotApi) {
this.task = checkNotNull(task, "Null task");
this.instance = checkNotNull(instance, "Null instance");
this.waveletName = checkNotNull(waveletName, "Null waveletName");
this.robotApi = checkNotNull(robotApi, "Null robotApi");
}
private Map<String, AttachmentId> getAttachmentsAndMapping(
Pair<GoogleWavelet, ImmutableList<GoogleDocument>> snapshot)
throws TaskCompleted {
GoogleWavelet wavelet = snapshot.getFirst();
List<GoogleDocument> documents = snapshot.getSecond();
log.info("Snapshot for " + waveletName + ": "
+ wavelet.getParticipantCount() + " participants, "
+ documents.size() + " documents");
log.info("Document ids: " + Lists.transform(documents,
new Function<GoogleDocument, String>() {
@Override public String apply(GoogleDocument doc) { return doc.getDocumentId(); }
}));
// Maps attachment ids (not document ids) to documents.
Map<String, GoogleDocument> attachmentDocs = getAttachmentDocs(documents);
if (attachmentDocs.isEmpty()) {
log.info("No attachments");
return ImmutableMap.of();
} else if (task.getAttachmentSize() > 0) {
Map<String, AttachmentId> attachmentMapping = buildAttachmentMapping(task);
log.info("Attachments already imported; importing with attachment mapping "
+ attachmentMapping);
return attachmentMapping;
} else {
log.info("Found attachmend ids " + attachmentDocs.keySet());
// Replace this task with one that fetches attachments and then imports.
FetchAttachmentsAndImportWaveletTask newTask =
new FetchAttachmentsAndImportWaveletTaskGsonImpl();
newTask.setOriginalImportTask(task);
populateAttachmentInfo(newTask, documents, attachmentDocs);
ImportTaskPayload payload = new ImportTaskPayloadGsonImpl();
payload.setFetchAttachmentsTask(newTask);
throw TaskCompleted.withFollowup(payload);
}
}
private void addToPerUserTable(CheckedTransaction tx, SlobId newId, boolean isPrivate)
throws RetryableFailure, PermanentFailure {
@Nullable RemoteConvWavelet entry =
perUserTable.getWavelet(tx, userId, instance, waveletName);
if (entry == null) {
log.warning("No per-user entry for " + waveletName + ", can't add " + newId);
return;
}
// We overwrite unconditionally here, since it's a corner case.
// TODO(ohler): think about this and explain what exactly is going on.
if (isPrivate) {
entry.setPrivateLocalId(newId);
} else {
entry.setSharedLocalId(newId);
}
perUserTable.putWavelet(tx, userId, entry);
}
private void addToPerUserTableWithoutTx(final SlobId newId, final boolean isPrivate)
throws PermanentFailure {
new RetryHelper().run(
new RetryHelper.VoidBody() {
@Override public void run() throws RetryableFailure, PermanentFailure {
CheckedTransaction tx = datastore.beginTransaction();
try {
addToPerUserTable(tx, newId, isPrivate);
tx.commit();
} finally {
tx.close();
}
}
});
}
// Returns false iff already unlocked.
private boolean unlockWavelet(CheckedTransaction tx, SlobId convId)
throws RetryableFailure, PermanentFailure {
ConvMetadataGsonImpl metadata = convMetadataStore.get(tx, convId);
Assert.check(metadata.hasImportMetadata(), "%s: Metadata has no import: %s",
convId, metadata);
if (metadata.getImportMetadata().getImportFinished()) {
log.info(convId + ": already unlocked");
return false;
}
ImportMetadata importMetadata = metadata.getImportMetadata();
importMetadata.setImportFinished(true);
metadata.setImportMetadata(importMetadata);
log.info(convId + ": unlocking");
convMetadataStore.put(tx, convId, metadata);
return true;
}
private ClientId getFakeClientId() {
return new ClientId("");
}
private void ensureParticipant(final SlobId convId) throws PermanentFailure {
new RetryHelper().run(
new RetryHelper.VoidBody() {
@Override public void run() throws RetryableFailure, PermanentFailure {
CheckedTransaction tx = datastore.beginTransaction();
try {
ConvMetadata metadata = convMetadataStore.get(tx, convId);
Assert.check(metadata.hasImportMetadata(), "%s: Metadata has no import: %s",
convId, metadata);
Assert.check(metadata.getImportMetadata().getImportFinished(),
"%s: still importing: %s", convId, metadata);
MutationLog l = convSlobFacilities.getMutationLogFactory().create(tx, convId);
StateAndVersion stateAndVersion = l.reconstruct(null);
Assert.check(stateAndVersion.getVersion() > 0, "%s at version 0: %s",
convId, stateAndVersion);
// TODO(ohler): use generics to avoid the cast
ReadableWaveletObject state = (ReadableWaveletObject) stateAndVersion.getState();
if (state.getParticipants().contains(importingUser)) {
log.info(importingUser + " is a participant at version "
+ stateAndVersion.getVersion());
return;
}
WaveletOperation op =
HistorySynthesizer.newAddParticipant(importingUser.getAddress(),
// We preserve last modified time to avoid re-ordering people's inboxes
// just because another participant imported.
state.getLastModifiedMillis(),
importingUser.getAddress());
log.info(importingUser + " is not a participant at version "
+ stateAndVersion.getVersion() + ", adding " + op);
MutationLog.Appender appender = l.prepareAppender().getAppender();
try {
appender.append(
new ChangeData<String>(getFakeClientId(), SERIALIZER.serializeDelta(op)));
} catch (ChangeRejected e) {
throw new RuntimeException("Appender rejected AddParticipant: " + op);
}
// TODO(ohler): Share more code with LocalMutationProcessor; having to call this
// stuff here rather than just commit() is error-prone.
appender.finish();
convSlobFacilities.getLocalMutationProcessor().runPreCommit(tx, convId, appender);
convSlobFacilities.getLocalMutationProcessor().schedulePostCommit(
tx, convId, appender);
tx.commit();
} finally {
tx.close();
}
}
});
}
private class ConvHistoryWriter {
// TODO(ohler): tune this.
private static final int BATCH_SIZE = 100;
private final SlobId slobId;
private final List<ChangeData<String>> buffer = Lists.newArrayListWithCapacity(BATCH_SIZE);
public ConvHistoryWriter(SlobId slobId) {
this.slobId = checkNotNull(slobId, "Null slobId");
}
private void flush() throws PermanentFailure, ChangeRejected {
@Nullable ChangeRejected rejected = new RetryHelper().run(
new RetryHelper.Body<ChangeRejected>() {
@Override public ChangeRejected run() throws RetryableFailure, PermanentFailure {
CheckedTransaction tx = datastore.beginTransaction();
try {
MutationLog mutationLog = convSlobFacilities.getMutationLogFactory().create(
tx, slobId);
MutationLog.Appender appender = mutationLog.prepareAppender().getAppender();
try {
appender.appendAll(buffer);
} catch (ChangeRejected e) {
return e;
}
appender.finish();
tx.commit();
return null;
} finally {
tx.close();
}
}
});
if (rejected != null) {
throw rejected;
}
buffer.clear();
}
public void append(WaveletOperation op) throws PermanentFailure, ChangeRejected {
if (buffer.size() >= BATCH_SIZE) {
flush();
}
buffer.add(new ChangeData<String>(getFakeClientId(), SERIALIZER.serializeDelta(op)));
}
public void append(List<WaveletOperation> ops) throws PermanentFailure, ChangeRejected {
for (WaveletOperation op : ops) {
append(op);
}
}
public void finish() throws PermanentFailure, ChangeRejected {
flush();
}
}
private void doImport() throws TaskCompleted, PermanentFailure, IOException {
// Fetch the wavelet. Even if this is a shared import and the wavelet is
// already imported, we have to do this fetch before re-using the existing
// wavelet, to confirm that the user has access to the wavelet on the remote
// instance.
Pair<GoogleWavelet, ImmutableList<GoogleDocument>> snapshot =
// We convertGooglewaveToGmail here since we do a lot of checks on the
// participant list below, and it's easier if it's already converted.
convertGooglewaveToGmail(robotApi.getSnapshot(waveletName));
GoogleWavelet wavelet = snapshot.getFirst();
log.info("Snapshot fetch succeeded: version " + wavelet.getVersion() + ", "
+ wavelet.getParticipantCount() + " participants: " + wavelet.getParticipantList());
final boolean isPrivate;
switch (task.getSettings().getSharingMode()) {
case PRIVATE:
isPrivate = true;
break;
case SHARED:
isPrivate = false;
break;
case PRIVATE_UNLESS_PARTICIPANT:
isPrivate = !wavelet.getParticipantList().contains(importingUser.getAddress());
break;
default:
throw new AssertionError("Unexpected ImportSharingMode: "
+ task.getSettings().getSharingMode());
}
// Look up if already imported according to PerUserTable; if so, we have nothing to do.
boolean alreadyImportedForThisUser = new RetryHelper().run(
new RetryHelper.Body<Boolean>() {
@Override public Boolean run() throws RetryableFailure, PermanentFailure {
CheckedTransaction tx = datastore.beginTransaction();
try {
@Nullable RemoteConvWavelet entry =
perUserTable.getWavelet(tx, userId, instance, waveletName);
if (isPrivate) {
if (entry != null && entry.getPrivateLocalId() != null
&& !(task.hasExistingSlobIdToIgnore()
&& new SlobId(task.getExistingSlobIdToIgnore()).equals(
entry.getPrivateLocalId()))) {
log.info("Private import already exists, aborting: " + entry);
return true;
} else {
return false;
}
} else {
if (entry != null && entry.getSharedLocalId() != null
&& !(task.hasExistingSlobIdToIgnore()
&& new SlobId(task.getExistingSlobIdToIgnore()).equals(
entry.getSharedLocalId()))) {
log.info("Shared import already exists, aborting: " + entry);
return true;
} else {
return false;
}
}
} finally {
tx.close();
}
}
});
if (alreadyImportedForThisUser) {
throw TaskCompleted.noFollowup();
}
if (!isPrivate) {
@Nullable SlobId existingSharedImport =
sharedImportTable.lookupWithoutTx(instance, waveletName);
if (existingSharedImport != null
&& !(task.hasExistingSlobIdToIgnore()
&& new SlobId(task.getExistingSlobIdToIgnore()).equals(existingSharedImport))) {
log.info("Found existing shared import " + existingSharedImport + ", re-using");
ensureParticipant(existingSharedImport);
addToPerUserTableWithoutTx(existingSharedImport, isPrivate);
throw TaskCompleted.noFollowup();
}
}
Map<String, AttachmentId> attachmentMapping = getAttachmentsAndMapping(snapshot);
List<WaveletOperation> participantFixup = Lists.newArrayList();
if (isPrivate) {
for (String participant : ImmutableList.copyOf(wavelet.getParticipantList())) {
participantFixup.add(
HistorySynthesizer.newRemoveParticipant(importingUser.getAddress(),
wavelet.getLastModifiedTimeMillis(), participant));
}
participantFixup.add(
HistorySynthesizer.newAddParticipant(importingUser.getAddress(),
wavelet.getLastModifiedTimeMillis(), importingUser.getAddress()));
} else {
if (!wavelet.getParticipantList().contains(importingUser.getAddress())) {
log.info(
importingUser + " is not a participant, adding: " + wavelet.getParticipantList());
participantFixup.add(
HistorySynthesizer.newAddParticipant(importingUser.getAddress(),
wavelet.getLastModifiedTimeMillis(), importingUser.getAddress()));
}
}
log.info("participantFixup=" + participantFixup);
boolean preserveHistory = !task.getSettings().getSynthesizeHistory();
log.info("preserveHistory=" + preserveHistory);
ImportMetadata importMetadata = new ImportMetadataGsonImpl();
importMetadata.setImportBeginTimeMillis(System.currentTimeMillis());
importMetadata.setImportFinished(false);
importMetadata.setOriginalImporter(userId.getId());
importMetadata.setSourceInstance(instance.serialize());
importMetadata.setRemoteWaveId(waveletName.waveId.serialise());
importMetadata.setRemoteWaveletId(waveletName.waveletId.serialise());
importMetadata.setRemoteHistoryCopied(preserveHistory);
importMetadata.setRemoteVersionImported(snapshot.getFirst().getVersion());
ConvMetadataGsonImpl convMetadata = new ConvMetadataGsonImpl();
convMetadata.setImportMetadata(importMetadata);
final SlobId newId;
if (!preserveHistory) {
List<WaveletOperation> initialHistory = Lists.newArrayList();
WaveletHistoryConverter converter = new WaveletHistoryConverter(
getConvNindoConverter(attachmentMapping));
for (WaveletOperation op :
new HistorySynthesizer().synthesizeHistory(wavelet, snapshot.getSecond())) {
initialHistory.add(converter.convertAndApply(convertGooglewaveToGmail(op)));
}
initialHistory.addAll(participantFixup);
newId = waveletCreator.newConvWithGeneratedId(initialHistory, convMetadata, true);
} else {
long version = 0;
newId = waveletCreator.newConvWithGeneratedId(
ImmutableList.<WaveletOperation>of(), convMetadata, true);
ConvHistoryWriter historyWriter = new ConvHistoryWriter(newId);
WaveletHistoryConverter converter =
new WaveletHistoryConverter(getConvNindoConverter(attachmentMapping));
try {
// NOTE(ohler): We have to stop at snapshot.getFirst().getVersion() even if
// getRawDeltas gives us more, since otherwise, participantFixup may be out-of-date.
while (version < snapshot.getFirst().getVersion()) {
List<ProtocolAppliedWaveletDelta> rawDeltas =
robotApi.getRawDeltas(waveletName, version);
for (ProtocolAppliedWaveletDelta rawDelta : rawDeltas) {
WaveletDelta delta = CoreWaveletOperationSerializer.deserialize(ProtocolWaveletDelta
.parseFrom(rawDelta.getSignedOriginalDelta().getDelta()));
for (WaveletOperation op : delta) {
WaveletOperation converted =
converter.convertAndApply(convertGooglewaveToGmail(op));
//log.info(version + ": " + op + " -> " + converted);
historyWriter.append(converted);
version++;
}
}
}
historyWriter.append(participantFixup);
historyWriter.finish();
} catch (ChangeRejected e) {
log.log(Level.SEVERE, "Change rejected somewhere at or before version " + version
+ ", re-importing without history", e);
ImportSettings settings = task.getSettings();
settings.setSynthesizeHistory(true);
task.setSettings(settings);
throw TaskCompleted.withFollowup(task);
}
}
log.info("Imported wavelet " + waveletName + " as local id " + newId);
boolean abandonAndRetry = new RetryHelper().run(
new RetryHelper.Body<Boolean>() {
@Override public Boolean run() throws RetryableFailure, PermanentFailure {
CheckedTransaction tx = datastore.beginTransactionXG();
try {
if (!isPrivate) {
@Nullable SlobId existingSharedImport =
sharedImportTable.lookup(tx, instance, waveletName);
if (existingSharedImport != null
&& !(task.hasExistingSlobIdToIgnore()
&& new SlobId(task.getExistingSlobIdToIgnore()).equals(
existingSharedImport))) {
log.warning("Found existing shared import " + existingSharedImport
+ ", abandoning import and retrying");
return true;
}
sharedImportTable.put(tx, instance, waveletName, newId);
}
if (!unlockWavelet(tx, newId)) {
// Already unlocked, which means this transaction is a spurious retry.
// Nothing to do.
return false;
}
addToPerUserTable(tx, newId, isPrivate);
// We don't want to run the immediate post-commit actions in this task
// since we don't want this task to fail if they crash. So we
// just schedule a task unconditionally.
//
// TODO(ohler): Decide what to do about pre-commit actions. Maybe we should
// run them here?
convSlobFacilities.getPostCommitActionScheduler()
.unconditionallyScheduleTask(tx, newId);
tx.commit();
return false;
} finally {
tx.close();
}
}
});
if (abandonAndRetry) {
throw TaskCompleted.withFollowup(task);
}
log.info("Completed");
throw TaskCompleted.noFollowup();
}
}
public List<ImportTaskPayload> importWavelet(ImportWaveletTask task)
throws IOException, PermanentFailure {
SourceInstance instance = sourceInstanceFactory.parseUnchecked(task.getInstance());
try {
new ImportContext(task, instance,
WaveletName.of(
WaveId.deserialise(task.getWaveId()),
WaveletId.deserialise(task.getWaveletId())),
robotApiFactory.create(instance.getApiUrl()))
.doImport();
throw new AssertionError("import() did not throw TaskCompleted");
} catch (TaskCompleted e) {
return e.followupTasks;
}
}
}
| 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.server.googleimport;
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 import tasks.
*
* @author ohler@google.com (Christian Ohler)
*/
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface ImportTaskQueue {}
| 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.server.googleimport;
import com.google.common.base.Preconditions;
import org.joda.time.DateMidnight;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;
/**
* Utilities for working with days since Unix epoch.
*
* @author ohler@google.com (Christian Ohler)
*/
public class DaysSinceEpoch {
public static final long MILLIS_PER_DAY = 24L * 60 * 60 * 1000;
private DaysSinceEpoch() {}
public static long fromYMD(int y, int m, int d) {
// Go through a LocalDate in the unverified hope that it will do
// something smart about out-of-range arguments.
return fromLocalDate(new LocalDate(y, m, d));
}
public static long fromLocalDate(LocalDate d) {
return fromDateMidnight(d.toDateMidnight(DateTimeZone.UTC));
}
// This one is private since there is no guarantee that the DateMidnight is in
// UTC time zone.
private static long fromDateMidnight(DateMidnight d) {
return fromMillis(d.getMillis());
}
public static long fromMillis(long millis) {
// Note that Unix time ignores leap seconds.
Preconditions.checkArgument(millis % MILLIS_PER_DAY == 0,
"Not a multiple of %s: %s", MILLIS_PER_DAY, millis);
return millis / MILLIS_PER_DAY;
}
public static DateMidnight toDateMidnightUTC(long daysSinceEpoch) {
return new DateMidnight(daysSinceEpoch * MILLIS_PER_DAY, DateTimeZone.UTC);
}
public static LocalDate toLocalDate(long daysSinceEpoch) {
return toDateMidnightUTC(daysSinceEpoch).toLocalDate();
}
}
| 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.server.googleimport;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.common.primitives.Ints;
import com.google.inject.Inject;
import com.google.walkaround.proto.FindRemoteWavesTask;
import com.google.walkaround.proto.ImportSettings;
import com.google.walkaround.proto.ImportTaskPayload;
import com.google.walkaround.proto.ImportWaveletTask;
import com.google.walkaround.proto.RobotSearchDigest;
import com.google.walkaround.proto.gson.FindRemoteWavesTaskGsonImpl;
import com.google.walkaround.proto.gson.ImportTaskPayloadGsonImpl;
import com.google.walkaround.proto.gson.ImportWaveletTaskGsonImpl;
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.shared.Assert;
import com.google.walkaround.wave.server.auth.StableUserId;
import com.google.walkaround.wave.server.gxp.SourceInstance;
import org.joda.time.LocalDate;
import org.waveprotocol.wave.model.id.IdUtil;
import org.waveprotocol.wave.model.id.WaveId;
import org.waveprotocol.wave.model.id.WaveletId;
import org.waveprotocol.wave.model.util.Pair;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Processes a {@link FindRemoteWavesTask}.
*
* @author ohler@google.com (Christian Ohler)
*/
public class FindRemoteWavesProcessor {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(FindRemoteWavesProcessor.class.getName());
private final RobotApi.Factory robotApiFactory;
private final SourceInstance.Factory sourceInstanceFactory;
private final StableUserId userId;
private final PerUserTable perUserTable;
private final CheckedDatastore datastore;
private final Random random;
@Inject
public FindRemoteWavesProcessor(RobotApi.Factory robotApiFactory,
SourceInstance.Factory sourceInstanceFactory,
StableUserId userId,
PerUserTable perUserTable,
CheckedDatastore datastore,
Random random) {
this.robotApiFactory = robotApiFactory;
this.sourceInstanceFactory = sourceInstanceFactory;
this.userId = userId;
this.perUserTable = perUserTable;
this.datastore = datastore;
this.random = random;
}
// This used to be 300 but has been raised. Some of the comments elsewhere in
// the code probably still assume 300.
private static final int MAX_RESULTS = 10000;
private String getQueryDateRestriction(String facet, long dateDays) {
LocalDate date = DaysSinceEpoch.toLocalDate(dateDays);
return String.format("%s:%04d/%02d/%02d", facet,
date.getYear(), date.getMonthOfYear(), date.getDayOfMonth());
}
private List<RobotSearchDigest> searchBetween(SourceInstance instance,
long onOrAfterDays, long beforeDays) throws IOException {
RobotApi api = robotApiFactory.create(instance.getApiUrl());
String query = getQueryDateRestriction("after", onOrAfterDays)
// The "before" search operator is inclusive (i.e., it means before the
// end of the day); beforeDays is exclusive.
+ " " + getQueryDateRestriction("before", beforeDays - 1);
return api.search(query, 0, MAX_RESULTS);
}
private long randomBetween(long min, long limit) {
return min + random.nextInt(Ints.checkedCast(limit - min));
}
private List<Pair<Long, Long>> splitInterval(long onOrAfterDays, long beforeDays) {
Preconditions.checkArgument(onOrAfterDays < beforeDays - 1,
"Interval invalid or too small to split further: %s, %s", onOrAfterDays, beforeDays);
// Split into roughly 5 intervals (if possible) because we want a high
// branching factor (300*5^n reaches 1000, 10000 etc. quite a bit faster
// than 300*2^n) and the maximum number of tasks GAE lets us add in one
// transaction is 5.
//
// TreeSet for iteration order.
Set<Long> splitPoints = Sets.newTreeSet();
for (int i = 0; i < 4; i++) {
// NOTE(ohler): Randomized strategy because it's simple to implement (the
// cases where beforeDays - onOrAfterDays < 5 would require some thought
// otherwise) and to make it unlikely that repeated runs send the same
// queries to the googlewave.com servers, which seem to have a bug where
// the result list is sometimes truncated for a query that has been issued
// previously with a lower maxResults limit (perhaps some incorrect
// caching). Randomization means that re-running the "find waves" step
// several times might have a greater chance to discover all waves. But
// I'm not positive whether this helps since I don't understand the bug.
//
// Other options include:
//
// * Instead of this interval splitting, start with "folder:3" or
// "before:2013/01/01" (for all waves), then do "before:<date of oldest
// wave returned by previous search>" until no more waves are returned.
// However, this relies on the assumption that truncated result lists
// are always truncated in such a way that only old waves are missing,
// not new waves. We'd have to verify this. Also, it's completely
// sequential rather than parallelizable.
//
// * Follow up every search for "after:A before:B" with another a search
// for "after:A before:<date of oldest wave returned by previous
// search>". This could be a good combination of the two but relies on
// the same assumption and adds quite a bit more code.
//
// * When the user triggers the "find remote waves" task, enqueue N of
// them rather than just one, to cover the search space N times with
// different random interval splits to improve the likelihood that we
// find everything. Could be good as well but adds code.
//
// * Add random negative search terms like -dgzimhmcoblhqfjciezc to the
// query that are unlikely to restrict the result set but make the query
// unique to avoid the poisoned caches. Could also do many different
// such searches and merge the result sets. (Can't assert that they are
// the same since waves may have been modified and fallen out of the
// date range.) Probably worth implementing.
//
// * Fix the bug in googlewave.com or demonstrate that it's not
// reproducible. Unlikely to happen since it's harder than any of these
// workarounds.
splitPoints.add(randomBetween(onOrAfterDays + 1, beforeDays));
}
splitPoints.add(beforeDays);
ImmutableList.Builder<Pair<Long, Long>> out = ImmutableList.builder();
long left = onOrAfterDays;
for (long right : splitPoints) {
Assert.check(left < right, "left=%s, right=%s", left, right);
out.add(Pair.of(left, right));
left = right;
}
return out.build();
}
private List<ImportTaskPayload> makeTasks(
SourceInstance instance, List<Pair<Long, Long>> intervals,
@Nullable ImportSettings autoImportSettings) {
log.info("intervals=" + intervals + ", settings=" + autoImportSettings);
ImmutableList.Builder<ImportTaskPayload> accu = ImmutableList.builder();
for (Pair<Long, Long> interval : intervals) {
FindRemoteWavesTask task = new FindRemoteWavesTaskGsonImpl();
task.setInstance(instance.serialize());
task.setOnOrAfterDays(interval.getFirst());
task.setBeforeDays(interval.getSecond());
if (autoImportSettings != null) {
task.setAutoImportSettings(autoImportSettings);
}
ImportTaskPayload payload = new ImportTaskPayloadGsonImpl();
payload.setFindWavesTask(task);
accu.add(payload);
}
return accu.build();
}
public List<ImportTaskPayload> makeRandomTasksForInterval(SourceInstance instance,
long onOrAfterDays, long beforeDays, @Nullable ImportSettings autoImportSettings) {
if (onOrAfterDays == beforeDays - 1) {
return makeTasks(instance, ImmutableList.of(Pair.of(onOrAfterDays, beforeDays)),
autoImportSettings);
} else {
return makeTasks(instance, splitInterval(onOrAfterDays, beforeDays),
autoImportSettings);
}
}
// Transaction limit is 500 entities but let's stay well below that.
private static final int MAX_WAVELETS_PER_TRANSACTION = 300;
private void storeResults(List<RemoteConvWavelet> results) throws PermanentFailure {
for (final List<RemoteConvWavelet> partition
: Iterables.partition(results, MAX_WAVELETS_PER_TRANSACTION)) {
new RetryHelper().run(
new RetryHelper.VoidBody() {
@Override public void run() throws RetryableFailure, PermanentFailure {
CheckedTransaction tx = datastore.beginTransaction();
try {
if (perUserTable.addRemoteWavelets(tx, userId, partition)) {
tx.commit();
}
} finally {
tx.close();
}
}
});
}
log.info("Successfully added " + results.size() + " remote waves");
}
private void scheduleImportTasks(List<RemoteConvWavelet> results,
final ImportSettings autoImportSettings) throws PermanentFailure {
for (final List<RemoteConvWavelet> partition : Iterables.partition(results,
// 5 tasks per transaction.
5)) {
new RetryHelper().run(
new RetryHelper.VoidBody() {
@Override public void run() throws RetryableFailure, PermanentFailure {
CheckedTransaction tx = datastore.beginTransaction();
try {
for (RemoteConvWavelet wavelet : partition) {
ImportWaveletTask task = new ImportWaveletTaskGsonImpl();
task.setInstance(wavelet.getSourceInstance().serialize());
task.setWaveId(wavelet.getDigest().getWaveId());
task.setWaveletId(wavelet.getWaveletId().serialise());
task.setSettings(autoImportSettings);
ImportTaskPayload payload = new ImportTaskPayloadGsonImpl();
payload.setImportWaveletTask(task);
perUserTable.addTask(tx, userId, payload);
}
tx.commit();
} finally {
tx.close();
}
}
});
}
log.info("Successfully scheduled import of " + results.size() + " waves");
}
private List<RemoteConvWavelet> expandPrivateReplies(SourceInstance instance,
List<RobotSearchDigest> digests) throws IOException {
RobotApi api = robotApiFactory.create(instance.getApiUrl());
ImmutableList.Builder<RemoteConvWavelet> wavelets = ImmutableList.builder();
for (RobotSearchDigest digest : digests) {
WaveId waveId = WaveId.deserialise(digest.getWaveId());
// The robot API only allows access to waves with ids that start with "w".
if (!waveId.getId().startsWith(IdUtil.WAVE_PREFIX + "+")) {
log.info("Wave " + waveId + " not accessible through Robot API, skipping");
} else {
log.info("Getting wave view for " + waveId);
List<WaveletId> waveletIds = api.getWaveView(waveId);
log.info("Wave view for " + waveId + ": " + waveletIds);
for (WaveletId waveletId : waveletIds) {
if (IdUtil.isConversationalId(waveletId)) {
wavelets.add(new RemoteConvWavelet(instance, digest, waveletId, null, null));
} else {
log.info("Skipping non-conv wavelet " + waveletId);
}
}
}
}
return wavelets.build();
}
public List<ImportTaskPayload> findWaves(FindRemoteWavesTask task)
throws IOException, PermanentFailure {
SourceInstance instance = sourceInstanceFactory.parseUnchecked(task.getInstance());
long onOrAfterDays = task.getOnOrAfterDays();
long beforeDays = task.getBeforeDays();
List<RobotSearchDigest> results = searchBetween(instance, onOrAfterDays, beforeDays);
List<RemoteConvWavelet> wavelets = expandPrivateReplies(instance, results);
@Nullable ImportSettings autoImportSettings =
task.hasAutoImportSettings() ? task.getAutoImportSettings() : null;
log.info("Search found " + results.size() + " waves, " + wavelets.size() + " wavelets");
if (results.isEmpty()) {
return ImmutableList.of();
}
storeResults(wavelets);
if (autoImportSettings != null) {
scheduleImportTasks(wavelets, autoImportSettings);
}
if (results.size() >= MAX_RESULTS) {
// Result list is most likely truncated, repeat with smaller intervals.
log.info("Got " + results.size() + " results between " + onOrAfterDays + " and " + beforeDays
+ ", splitting");
if (beforeDays - onOrAfterDays <= 1) {
throw new RuntimeException("Can't split further; too many results (" + results.size()
+ ") between " + onOrAfterDays + " and " + beforeDays);
}
return makeRandomTasksForInterval(instance, onOrAfterDays, beforeDays, autoImportSettings);
} else {
return ImmutableList.of();
}
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.