process.cc 22 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <v8.h>
29

30 31 32
#include <string>
#include <map>

33 34 35 36
#ifdef COMPRESS_STARTUP_DATA_BZ2
#error Using compressed startup data is not supported for this sample
#endif

37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
using namespace std;
using namespace v8;

// These interfaces represent an existing request processing interface.
// The idea is to imagine a real application that uses these interfaces
// and then add scripting capabilities that allow you to interact with
// the objects through JavaScript.

/**
 * A simplified http request.
 */
class HttpRequest {
 public:
  virtual ~HttpRequest() { }
  virtual const string& Path() = 0;
  virtual const string& Referrer() = 0;
  virtual const string& Host() = 0;
  virtual const string& UserAgent() = 0;
};

57

58 59 60 61 62 63 64 65 66 67
/**
 * The abstract superclass of http request processors.
 */
class HttpRequestProcessor {
 public:
  virtual ~HttpRequestProcessor() { }

  // Initialize this processor.  The map contains options that control
  // how requests should be processed.
  virtual bool Initialize(map<string, string>* options,
68
                          map<string, string>* output) = 0;
69 70 71 72 73 74 75

  // Process a single request.
  virtual bool Process(HttpRequest* req) = 0;

  static void Log(const char* event);
};

76

77 78 79 80 81 82 83
/**
 * An http request processor that is scriptable using JavaScript.
 */
class JsHttpRequestProcessor : public HttpRequestProcessor {
 public:
  // Creates a new processor that processes requests by invoking the
  // Process function of the JavaScript script given as an argument.
84 85
  JsHttpRequestProcessor(Isolate* isolate, Handle<String> script)
      : isolate_(isolate), script_(script) { }
86 87 88
  virtual ~JsHttpRequestProcessor();

  virtual bool Initialize(map<string, string>* opts,
89
                          map<string, string>* output);
90 91 92
  virtual bool Process(HttpRequest* req);

 private:
93 94
  // Execute the script associated with this processor and extract the
  // Process function.  Returns true if this succeeded, otherwise false.
95 96 97 98 99 100 101 102
  bool ExecuteScript(Handle<String> script);

  // Wrap the options and output map in a JavaScript objects and
  // install it in the global namespace as 'options' and 'output'.
  bool InstallMaps(map<string, string>* opts, map<string, string>* output);

  // Constructs the template that describes the JavaScript wrapper
  // type for requests.
103 104
  static Handle<ObjectTemplate> MakeRequestTemplate(Isolate* isolate);
  static Handle<ObjectTemplate> MakeMapTemplate(Isolate* isolate);
105 106

  // Callbacks that access the individual fields of request objects.
107 108 109 110 111 112 113 114
  static void GetPath(Local<String> name,
                      const PropertyCallbackInfo<Value>& info);
  static void GetReferrer(Local<String> name,
                          const PropertyCallbackInfo<Value>& info);
  static void GetHost(Local<String> name,
                      const PropertyCallbackInfo<Value>& info);
  static void GetUserAgent(Local<String> name,
                           const PropertyCallbackInfo<Value>& info);
115 116

  // Callbacks that access maps
117 118 119 120 121
  static void MapGet(Local<String> name,
                     const PropertyCallbackInfo<Value>& info);
  static void MapSet(Local<String> name,
                     Local<Value> value,
                     const PropertyCallbackInfo<Value>& info);
122 123 124

  // Utility methods for wrapping C++ objects as JavaScript objects,
  // and going back again.
125
  Handle<Object> WrapMap(map<string, string>* obj);
126
  static map<string, string>* UnwrapMap(Handle<Object> obj);
127
  Handle<Object> WrapRequest(HttpRequest* obj);
128 129
  static HttpRequest* UnwrapRequest(Handle<Object> obj);

130
  Isolate* GetIsolate() { return isolate_; }
131

132
  Isolate* isolate_;
133 134 135 136 137 138 139
  Handle<String> script_;
  Persistent<Context> context_;
  Persistent<Function> process_;
  static Persistent<ObjectTemplate> request_template_;
  static Persistent<ObjectTemplate> map_template_;
};

140

141 142 143 144 145
// -------------------------
// --- P r o c e s s o r ---
// -------------------------


146 147
static void LogCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
  if (args.Length() < 1) return;
148
  HandleScope scope(args.GetIsolate());
149
  Handle<Value> arg = args[0];
150
  String::Utf8Value value(arg);
151 152 153 154 155 156
  HttpRequestProcessor::Log(*value);
}


// Execute the script and fetch the Process method.
bool JsHttpRequestProcessor::Initialize(map<string, string>* opts,
157
                                        map<string, string>* output) {
158
  // Create a handle scope to hold the temporary references.
159
  HandleScope handle_scope(GetIsolate());
160 161 162

  // Create a template for the global object where we set the
  // built-in global functions.
163
  Handle<ObjectTemplate> global = ObjectTemplate::New(GetIsolate());
164
  global->Set(String::NewFromUtf8(GetIsolate(), "log"),
165
              FunctionTemplate::New(GetIsolate(), LogCallback));
166

167 168 169 170 171
  // Each processor gets its own context so different processors don't
  // affect each other. Context::New returns a persistent handle which
  // is what we need for the reference to remain after we return from
  // this method. That persistent handle has to be disposed in the
  // destructor.
172 173
  v8::Handle<v8::Context> context = Context::New(GetIsolate(), NULL, global);
  context_.Reset(GetIsolate(), context);
174 175 176

  // Enter the new context so all the following operations take place
  // within it.
177
  Context::Scope context_scope(context);
178 179 180 181 182 183 184 185 186 187 188

  // Make the options mapping available within the context
  if (!InstallMaps(opts, output))
    return false;

  // Compile and run the script
  if (!ExecuteScript(script_))
    return false;

  // The script compiled and ran correctly.  Now we fetch out the
  // Process function from the global object.
189
  Handle<String> process_name = String::NewFromUtf8(GetIsolate(), "Process");
190
  Handle<Value> process_val = context->Global()->Get(process_name);
191 192 193 194 195 196 197 198 199 200

  // If there is no Process function, or if it is not a function,
  // bail out
  if (!process_val->IsFunction()) return false;

  // It is a function; cast it to a Function
  Handle<Function> process_fun = Handle<Function>::Cast(process_val);

  // Store the function in a Persistent handle, since we also want
  // that to remain after this call returns
201
  process_.Reset(GetIsolate(), process_fun);
202 203 204 205 206 207 208

  // All done; all went well
  return true;
}


bool JsHttpRequestProcessor::ExecuteScript(Handle<String> script) {
209
  HandleScope handle_scope(GetIsolate());
210 211 212 213 214 215 216 217

  // We're just about to compile the script; set up an error handler to
  // catch any exceptions the script might throw.
  TryCatch try_catch;

  // Compile the script and check for errors.
  Handle<Script> compiled_script = Script::Compile(script);
  if (compiled_script.IsEmpty()) {
218
    String::Utf8Value error(try_catch.Exception());
219 220 221 222 223 224 225 226 227
    Log(*error);
    // The script failed to compile; bail out.
    return false;
  }

  // Run the script!
  Handle<Value> result = compiled_script->Run();
  if (result.IsEmpty()) {
    // The TryCatch above is still in effect and will have caught the error.
228
    String::Utf8Value error(try_catch.Exception());
229 230 231 232 233 234 235 236 237
    Log(*error);
    // Running the script failed; bail out.
    return false;
  }
  return true;
}


bool JsHttpRequestProcessor::InstallMaps(map<string, string>* opts,
238
                                         map<string, string>* output) {
239
  HandleScope handle_scope(GetIsolate());
240 241 242 243

  // Wrap the map object in a JavaScript wrapper
  Handle<Object> opts_obj = WrapMap(opts);

244 245 246
  v8::Local<v8::Context> context =
      v8::Local<v8::Context>::New(GetIsolate(), context_);

247
  // Set the options object as a property on the global object.
248 249
  context->Global()->Set(String::NewFromUtf8(GetIsolate(), "options"),
                         opts_obj);
250 251

  Handle<Object> output_obj = WrapMap(output);
252 253
  context->Global()->Set(String::NewFromUtf8(GetIsolate(), "output"),
                         output_obj);
254 255 256 257 258 259 260

  return true;
}


bool JsHttpRequestProcessor::Process(HttpRequest* request) {
  // Create a handle scope to keep the temporary object references.
261
  HandleScope handle_scope(GetIsolate());
262

263 264 265
  v8::Local<v8::Context> context =
      v8::Local<v8::Context>::New(GetIsolate(), context_);

266 267
  // Enter this processor's context so all the remaining operations
  // take place there
268
  Context::Scope context_scope(context);
269 270 271 272 273 274 275 276 277 278 279

  // Wrap the C++ request object in a JavaScript wrapper
  Handle<Object> request_obj = WrapRequest(request);

  // Set up an exception handler before calling the Process function
  TryCatch try_catch;

  // Invoke the process function, giving the global object as 'this'
  // and one argument, the request.
  const int argc = 1;
  Handle<Value> argv[argc] = { request_obj };
280 281 282
  v8::Local<v8::Function> process =
      v8::Local<v8::Function>::New(GetIsolate(), process_);
  Handle<Value> result = process->Call(context->Global(), argc, argv);
283
  if (result.IsEmpty()) {
284
    String::Utf8Value error(try_catch.Exception());
285 286 287 288 289 290 291 292 293 294 295 296
    Log(*error);
    return false;
  } else {
    return true;
  }
}


JsHttpRequestProcessor::~JsHttpRequestProcessor() {
  // Dispose the persistent handles.  When noone else has any
  // references to the objects stored in the handles they will be
  // automatically reclaimed.
297 298
  context_.Reset();
  process_.Reset();
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
}


Persistent<ObjectTemplate> JsHttpRequestProcessor::request_template_;
Persistent<ObjectTemplate> JsHttpRequestProcessor::map_template_;


// -----------------------------------
// --- A c c e s s i n g   M a p s ---
// -----------------------------------

// Utility function that wraps a C++ http request object in a
// JavaScript object.
Handle<Object> JsHttpRequestProcessor::WrapMap(map<string, string>* obj) {
  // Handle scope for temporary handles.
314
  EscapableHandleScope handle_scope(GetIsolate());
315 316 317

  // Fetch the template for creating JavaScript map wrappers.
  // It only has to be created once, which we do on demand.
318
  if (map_template_.IsEmpty()) {
319
    Handle<ObjectTemplate> raw_template = MakeMapTemplate(GetIsolate());
320
    map_template_.Reset(GetIsolate(), raw_template);
321
  }
322 323
  Handle<ObjectTemplate> templ =
      Local<ObjectTemplate>::New(GetIsolate(), map_template_);
324 325

  // Create an empty map wrapper.
326
  Local<Object> result = templ->NewInstance();
327 328 329

  // Wrap the raw C++ pointer in an External so it can be referenced
  // from within JavaScript.
330
  Handle<External> map_ptr = External::New(GetIsolate(), obj);
331 332 333 334 335 336 337 338

  // Store the map pointer in the JavaScript wrapper.
  result->SetInternalField(0, map_ptr);

  // Return the result through the current handle scope.  Since each
  // of these handles will go away when the handle scope is deleted
  // we need to call Close to let one, the result, escape into the
  // outer handle scope.
339
  return handle_scope.Escape(result);
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
}


// Utility function that extracts the C++ map pointer from a wrapper
// object.
map<string, string>* JsHttpRequestProcessor::UnwrapMap(Handle<Object> obj) {
  Handle<External> field = Handle<External>::Cast(obj->GetInternalField(0));
  void* ptr = field->Value();
  return static_cast<map<string, string>*>(ptr);
}


// Convert a JavaScript string to a std::string.  To not bother too
// much with string encodings we just use ascii.
string ObjectToString(Local<Value> value) {
355 356
  String::Utf8Value utf8_value(value);
  return string(*utf8_value);
357 358 359
}


360 361
void JsHttpRequestProcessor::MapGet(Local<String> name,
                                    const PropertyCallbackInfo<Value>& info) {
362 363 364 365 366 367 368 369 370 371
  // Fetch the map wrapped by this object.
  map<string, string>* obj = UnwrapMap(info.Holder());

  // Convert the JavaScript string to a std::string.
  string key = ObjectToString(name);

  // Look up the value if it exists using the standard STL ideom.
  map<string, string>::iterator iter = obj->find(key);

  // If the key is not present return an empty handle as signal
372
  if (iter == obj->end()) return;
373 374 375

  // Otherwise fetch the value and wrap it in a JavaScript string
  const string& value = (*iter).second;
376 377 378
  info.GetReturnValue().Set(String::NewFromUtf8(
      info.GetIsolate(), value.c_str(), String::kNormalString,
      static_cast<int>(value.length())));
379 380 381
}


382 383 384
void JsHttpRequestProcessor::MapSet(Local<String> name,
                                    Local<Value> value_obj,
                                    const PropertyCallbackInfo<Value>& info) {
385 386 387 388 389 390 391 392 393 394 395
  // Fetch the map wrapped by this object.
  map<string, string>* obj = UnwrapMap(info.Holder());

  // Convert the key and value to std::strings.
  string key = ObjectToString(name);
  string value = ObjectToString(value_obj);

  // Update the map.
  (*obj)[key] = value;

  // Return the value; any non-empty handle will work.
396
  info.GetReturnValue().Set(value_obj);
397 398 399
}


400 401
Handle<ObjectTemplate> JsHttpRequestProcessor::MakeMapTemplate(
    Isolate* isolate) {
402
  EscapableHandleScope handle_scope(isolate);
403

404
  Local<ObjectTemplate> result = ObjectTemplate::New(isolate);
405 406 407 408
  result->SetInternalFieldCount(1);
  result->SetNamedPropertyHandler(MapGet, MapSet);

  // Again, return the result through the current handle scope.
409
  return handle_scope.Escape(result);
410 411 412 413 414 415 416 417 418 419 420 421 422
}


// -------------------------------------------
// --- A c c e s s i n g   R e q u e s t s ---
// -------------------------------------------

/**
 * Utility function that wraps a C++ http request object in a
 * JavaScript object.
 */
Handle<Object> JsHttpRequestProcessor::WrapRequest(HttpRequest* request) {
  // Handle scope for temporary handles.
423
  EscapableHandleScope handle_scope(GetIsolate());
424 425 426 427

  // Fetch the template for creating JavaScript http request wrappers.
  // It only has to be created once, which we do on demand.
  if (request_template_.IsEmpty()) {
428
    Handle<ObjectTemplate> raw_template = MakeRequestTemplate(GetIsolate());
429
    request_template_.Reset(GetIsolate(), raw_template);
430
  }
431 432
  Handle<ObjectTemplate> templ =
      Local<ObjectTemplate>::New(GetIsolate(), request_template_);
433 434

  // Create an empty http request wrapper.
435
  Local<Object> result = templ->NewInstance();
436 437 438

  // Wrap the raw C++ pointer in an External so it can be referenced
  // from within JavaScript.
439
  Handle<External> request_ptr = External::New(GetIsolate(), request);
440 441 442 443 444 445 446 447

  // Store the request pointer in the JavaScript wrapper.
  result->SetInternalField(0, request_ptr);

  // Return the result through the current handle scope.  Since each
  // of these handles will go away when the handle scope is deleted
  // we need to call Close to let one, the result, escape into the
  // outer handle scope.
448
  return handle_scope.Escape(result);
449 450 451 452 453 454 455 456 457 458 459 460 461 462
}


/**
 * Utility function that extracts the C++ http request object from a
 * wrapper object.
 */
HttpRequest* JsHttpRequestProcessor::UnwrapRequest(Handle<Object> obj) {
  Handle<External> field = Handle<External>::Cast(obj->GetInternalField(0));
  void* ptr = field->Value();
  return static_cast<HttpRequest*>(ptr);
}


463 464
void JsHttpRequestProcessor::GetPath(Local<String> name,
                                     const PropertyCallbackInfo<Value>& info) {
465 466 467 468 469 470 471
  // Extract the C++ request object from the JavaScript wrapper.
  HttpRequest* request = UnwrapRequest(info.Holder());

  // Fetch the path.
  const string& path = request->Path();

  // Wrap the result in a JavaScript string and return it.
472 473 474
  info.GetReturnValue().Set(String::NewFromUtf8(
      info.GetIsolate(), path.c_str(), String::kNormalString,
      static_cast<int>(path.length())));
475 476 477
}


478 479 480
void JsHttpRequestProcessor::GetReferrer(
    Local<String> name,
    const PropertyCallbackInfo<Value>& info) {
481 482
  HttpRequest* request = UnwrapRequest(info.Holder());
  const string& path = request->Referrer();
483 484 485
  info.GetReturnValue().Set(String::NewFromUtf8(
      info.GetIsolate(), path.c_str(), String::kNormalString,
      static_cast<int>(path.length())));
486 487 488
}


489 490
void JsHttpRequestProcessor::GetHost(Local<String> name,
                                     const PropertyCallbackInfo<Value>& info) {
491 492
  HttpRequest* request = UnwrapRequest(info.Holder());
  const string& path = request->Host();
493 494 495
  info.GetReturnValue().Set(String::NewFromUtf8(
      info.GetIsolate(), path.c_str(), String::kNormalString,
      static_cast<int>(path.length())));
496 497 498
}


499 500 501
void JsHttpRequestProcessor::GetUserAgent(
    Local<String> name,
    const PropertyCallbackInfo<Value>& info) {
502 503
  HttpRequest* request = UnwrapRequest(info.Holder());
  const string& path = request->UserAgent();
504 505 506
  info.GetReturnValue().Set(String::NewFromUtf8(
      info.GetIsolate(), path.c_str(), String::kNormalString,
      static_cast<int>(path.length())));
507 508 509
}


510 511
Handle<ObjectTemplate> JsHttpRequestProcessor::MakeRequestTemplate(
    Isolate* isolate) {
512
  EscapableHandleScope handle_scope(isolate);
513

514
  Local<ObjectTemplate> result = ObjectTemplate::New(isolate);
515 516 517
  result->SetInternalFieldCount(1);

  // Add accessors for each of the fields of the request.
518 519 520 521 522 523 524 525 526 527 528 529
  result->SetAccessor(
      String::NewFromUtf8(isolate, "path", String::kInternalizedString),
      GetPath);
  result->SetAccessor(
      String::NewFromUtf8(isolate, "referrer", String::kInternalizedString),
      GetReferrer);
  result->SetAccessor(
      String::NewFromUtf8(isolate, "host", String::kInternalizedString),
      GetHost);
  result->SetAccessor(
      String::NewFromUtf8(isolate, "userAgent", String::kInternalizedString),
      GetUserAgent);
530 531

  // Again, return the result through the current handle scope.
532
  return handle_scope.Escape(result);
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
}


// --- Test ---


void HttpRequestProcessor::Log(const char* event) {
  printf("Logged: %s\n", event);
}


/**
 * A simplified http request.
 */
class StringHttpRequest : public HttpRequest {
 public:
549 550 551 552
  StringHttpRequest(const string& path,
                    const string& referrer,
                    const string& host,
                    const string& user_agent);
553 554 555 556 557 558 559 560 561 562 563 564 565
  virtual const string& Path() { return path_; }
  virtual const string& Referrer() { return referrer_; }
  virtual const string& Host() { return host_; }
  virtual const string& UserAgent() { return user_agent_; }
 private:
  string path_;
  string referrer_;
  string host_;
  string user_agent_;
};


StringHttpRequest::StringHttpRequest(const string& path,
566 567 568
                                     const string& referrer,
                                     const string& host,
                                     const string& user_agent)
569 570 571 572 573 574
    : path_(path),
      referrer_(referrer),
      host_(host),
      user_agent_(user_agent) { }


575 576 577 578
void ParseOptions(int argc,
                  char* argv[],
                  map<string, string>& options,
                  string* file) {
579 580
  for (int i = 1; i < argc; i++) {
    string arg = argv[i];
581
    size_t index = arg.find('=', 0);
582 583 584 585 586 587 588 589 590 591 592 593
    if (index == string::npos) {
      *file = arg;
    } else {
      string key = arg.substr(0, index);
      string value = arg.substr(index+1);
      options[key] = value;
    }
  }
}


// Reads a file into a v8 string.
594
Handle<String> ReadFile(Isolate* isolate, const string& name) {
595 596 597 598
  FILE* file = fopen(name.c_str(), "rb");
  if (file == NULL) return Handle<String>();

  fseek(file, 0, SEEK_END);
599
  int size = ftell(file);
600 601 602 603
  rewind(file);

  char* chars = new char[size + 1];
  chars[size] = '\0';
604
  for (int i = 0; i < size;) {
605
    int read = static_cast<int>(fread(&chars[i], 1, size - i, file));
606 607 608
    i += read;
  }
  fclose(file);
609 610
  Handle<String> result =
      String::NewFromUtf8(isolate, chars, String::kNormalString, size);
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
  delete[] chars;
  return result;
}


const int kSampleSize = 6;
StringHttpRequest kSampleRequests[kSampleSize] = {
  StringHttpRequest("/process.cc", "localhost", "google.com", "firefox"),
  StringHttpRequest("/", "localhost", "google.net", "firefox"),
  StringHttpRequest("/", "localhost", "google.org", "safari"),
  StringHttpRequest("/", "localhost", "yahoo.com", "ie"),
  StringHttpRequest("/", "localhost", "yahoo.com", "safari"),
  StringHttpRequest("/", "localhost", "yahoo.com", "firefox")
};


bool ProcessEntries(HttpRequestProcessor* processor, int count,
628
                    StringHttpRequest* reqs) {
629 630 631 632 633 634 635 636
  for (int i = 0; i < count; i++) {
    if (!processor->Process(&reqs[i]))
      return false;
  }
  return true;
}


637 638
void PrintMap(map<string, string>* m) {
  for (map<string, string>::iterator i = m->begin(); i != m->end(); i++) {
639 640 641 642 643 644 645
    pair<string, string> entry = *i;
    printf("%s: %s\n", entry.first.c_str(), entry.second.c_str());
  }
}


int main(int argc, char* argv[]) {
646
  v8::V8::InitializeICU();
647 648 649 650 651 652 653
  map<string, string> options;
  string file;
  ParseOptions(argc, argv, options, &file);
  if (file.empty()) {
    fprintf(stderr, "No script was specified.\n");
    return 1;
  }
654 655
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);
656
  Handle<String> source = ReadFile(isolate, file);
657 658 659 660
  if (source.IsEmpty()) {
    fprintf(stderr, "Error reading '%s'.\n", file.c_str());
    return 1;
  }
661
  JsHttpRequestProcessor processor(isolate, source);
662 663 664 665 666 667 668
  map<string, string> output;
  if (!processor.Initialize(&options, &output)) {
    fprintf(stderr, "Error initializing processor.\n");
    return 1;
  }
  if (!ProcessEntries(&processor, kSampleSize, kSampleRequests))
    return 1;
669
  PrintMap(&output);
670
}