content_handler_demo.cc revision 1320f92c476a1ad9d19dba2a48c72b75566198e9
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. 4 5#include <stdio.h> 6 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" 11 12namespace mojo { 13namespace examples { 14 15class ContentHandlerApp; 16 17class ContentHandlerImpl : public InterfaceImpl<ContentHandler> { 18 public: 19 explicit ContentHandlerImpl(ContentHandlerApp* content_handler_app) 20 : content_handler_app_(content_handler_app) { 21 } 22 virtual ~ContentHandlerImpl() {} 23 24 private: 25 virtual void OnConnect(const mojo::String& url, 26 URLResponsePtr response, 27 InterfaceRequest<ServiceProvider> service_provider) 28 MOJO_OVERRIDE; 29 30 ContentHandlerApp* content_handler_app_; 31}; 32 33class ContentHandlerApp : public ApplicationDelegate { 34 public: 35 ContentHandlerApp() : content_handler_factory_(this) { 36 } 37 38 virtual void Initialize(ApplicationImpl* app) MOJO_OVERRIDE { 39 } 40 41 virtual bool ConfigureIncomingConnection(ApplicationConnection* connection) 42 MOJO_OVERRIDE { 43 connection->AddService(&content_handler_factory_); 44 return true; 45 } 46 47 void PrintResponse(ScopedDataPipeConsumerHandle body) const { 48 for (;;) { 49 char buf[512]; 50 uint32_t num_bytes = sizeof(buf); 51 MojoResult result = ReadDataRaw(body.get(), buf, &num_bytes, 52 MOJO_READ_DATA_FLAG_NONE); 53 if (result == MOJO_RESULT_SHOULD_WAIT) { 54 Wait(body.get(), 55 MOJO_HANDLE_SIGNAL_READABLE, 56 MOJO_DEADLINE_INDEFINITE); 57 } else if (result == MOJO_RESULT_OK) { 58 if (fwrite(buf, num_bytes, 1, stdout) != 1) { 59 printf("\nUnexpected error writing to file\n"); 60 break; 61 } 62 } else { 63 break; 64 } 65 66 printf("\n>>> EOF <<<\n"); 67 } 68 } 69 70 private: 71 InterfaceFactoryImplWithContext<ContentHandlerImpl, 72 ContentHandlerApp> content_handler_factory_; 73}; 74 75void ContentHandlerImpl::OnConnect( 76 const mojo::String& url, 77 URLResponsePtr response, 78 InterfaceRequest<ServiceProvider> service_provider) { 79 printf("ContentHandler::OnConnect - url:%s - body follows\n\n", 80 url.To<std::string>().c_str()); 81 content_handler_app_->PrintResponse(response->body.Pass()); 82} 83 84} // namespace examples 85 86// static 87ApplicationDelegate* ApplicationDelegate::Create() { 88 return new examples::ContentHandlerApp(); 89} 90 91} // namespace mojo 92