[Drive] Handle error cases earlier in FakeDriveService
[chromium-blink-merge.git] / mojo / examples / content_handler_demo / content_handler_demo.cc
blob21864f75f474e90f1a2a301190334f799a4932a5
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include <stdio.h>
7 #include "mojo/public/cpp/application/application_delegate.h"
8 #include "mojo/public/cpp/application/application_impl.h"
9 #include "mojo/public/cpp/application/interface_factory_impl.h"
10 #include "mojo/services/public/interfaces/content_handler/content_handler.mojom.h"
12 namespace mojo {
13 namespace examples {
15 class ContentHandlerApp;
17 class ContentHandlerImpl : public InterfaceImpl<ContentHandler> {
18 public:
19 explicit ContentHandlerImpl(ContentHandlerApp* content_handler_app)
20 : content_handler_app_(content_handler_app) {
22 virtual ~ContentHandlerImpl() {}
24 private:
25 virtual void OnConnect(const mojo::String& url,
26 URLResponsePtr content,
27 ServiceProviderPtr service_provider) MOJO_OVERRIDE;
29 ContentHandlerApp* content_handler_app_;
32 class ContentHandlerApp : public ApplicationDelegate {
33 public:
34 ContentHandlerApp() : content_handler_factory_(this) {
37 virtual void Initialize(ApplicationImpl* app) MOJO_OVERRIDE {
40 virtual bool ConfigureIncomingConnection(ApplicationConnection* connection)
41 MOJO_OVERRIDE {
42 connection->AddService(&content_handler_factory_);
43 return true;
46 void PrintResponse(ScopedDataPipeConsumerHandle body) const {
47 for (;;) {
48 char buf[512];
49 uint32_t num_bytes = sizeof(buf);
50 MojoResult result = ReadDataRaw(body.get(), buf, &num_bytes,
51 MOJO_READ_DATA_FLAG_NONE);
52 if (result == MOJO_RESULT_SHOULD_WAIT) {
53 Wait(body.get(),
54 MOJO_HANDLE_SIGNAL_READABLE,
55 MOJO_DEADLINE_INDEFINITE);
56 } else if (result == MOJO_RESULT_OK) {
57 if (fwrite(buf, num_bytes, 1, stdout) != 1) {
58 printf("\nUnexpected error writing to file\n");
59 break;
61 } else {
62 break;
65 printf("\n>>> EOF <<<\n");
69 private:
70 InterfaceFactoryImplWithContext<ContentHandlerImpl,
71 ContentHandlerApp> content_handler_factory_;
74 void ContentHandlerImpl::OnConnect(const mojo::String& url,
75 URLResponsePtr content,
76 ServiceProviderPtr service_provider) {
77 printf("ContentHandler::OnConnect - url:%s - body follows\n\n",
78 url.To<std::string>().c_str());
79 content_handler_app_->PrintResponse(content->body.Pass());
82 } // namespace examples
84 // static
85 ApplicationDelegate* ApplicationDelegate::Create() {
86 return new examples::ContentHandlerApp();
89 } // namespace mojo