Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(233)

Side by Side Diff: samples/process.cc

Issue 1219133004: Remove usage of to-be-deprecated APIs from samples (Closed) Base URL: https://chromium.googlesource.com/v8/v8.git@master
Patch Set: Created 5 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « samples/hello-world.cc ('k') | samples/samples.gyp » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright 2012 the V8 project authors. All rights reserved. 1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without 2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are 3 // modification, are permitted provided that the following conditions are
4 // met: 4 // met:
5 // 5 //
6 // * Redistributions of source code must retain the above copyright 6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer. 7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above 8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following 9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided 10 // disclaimer in the documentation and/or other materials provided
(...skipping 75 matching lines...) Expand 10 before | Expand all | Expand 10 after
86 }; 86 };
87 87
88 88
89 /** 89 /**
90 * An http request processor that is scriptable using JavaScript. 90 * An http request processor that is scriptable using JavaScript.
91 */ 91 */
92 class JsHttpRequestProcessor : public HttpRequestProcessor { 92 class JsHttpRequestProcessor : public HttpRequestProcessor {
93 public: 93 public:
94 // Creates a new processor that processes requests by invoking the 94 // Creates a new processor that processes requests by invoking the
95 // Process function of the JavaScript script given as an argument. 95 // Process function of the JavaScript script given as an argument.
96 JsHttpRequestProcessor(Isolate* isolate, Handle<String> script) 96 JsHttpRequestProcessor(Isolate* isolate, Local<String> script)
97 : isolate_(isolate), script_(script) { } 97 : isolate_(isolate), script_(script) {}
98 virtual ~JsHttpRequestProcessor(); 98 virtual ~JsHttpRequestProcessor();
99 99
100 virtual bool Initialize(map<string, string>* opts, 100 virtual bool Initialize(map<string, string>* opts,
101 map<string, string>* output); 101 map<string, string>* output);
102 virtual bool Process(HttpRequest* req); 102 virtual bool Process(HttpRequest* req);
103 103
104 private: 104 private:
105 // Execute the script associated with this processor and extract the 105 // Execute the script associated with this processor and extract the
106 // Process function. Returns true if this succeeded, otherwise false. 106 // Process function. Returns true if this succeeded, otherwise false.
107 bool ExecuteScript(Handle<String> script); 107 bool ExecuteScript(Local<String> script);
108 108
109 // Wrap the options and output map in a JavaScript objects and 109 // Wrap the options and output map in a JavaScript objects and
110 // install it in the global namespace as 'options' and 'output'. 110 // install it in the global namespace as 'options' and 'output'.
111 bool InstallMaps(map<string, string>* opts, map<string, string>* output); 111 bool InstallMaps(map<string, string>* opts, map<string, string>* output);
112 112
113 // Constructs the template that describes the JavaScript wrapper 113 // Constructs the template that describes the JavaScript wrapper
114 // type for requests. 114 // type for requests.
115 static Handle<ObjectTemplate> MakeRequestTemplate(Isolate* isolate); 115 static Local<ObjectTemplate> MakeRequestTemplate(Isolate* isolate);
116 static Handle<ObjectTemplate> MakeMapTemplate(Isolate* isolate); 116 static Local<ObjectTemplate> MakeMapTemplate(Isolate* isolate);
117 117
118 // Callbacks that access the individual fields of request objects. 118 // Callbacks that access the individual fields of request objects.
119 static void GetPath(Local<String> name, 119 static void GetPath(Local<String> name,
120 const PropertyCallbackInfo<Value>& info); 120 const PropertyCallbackInfo<Value>& info);
121 static void GetReferrer(Local<String> name, 121 static void GetReferrer(Local<String> name,
122 const PropertyCallbackInfo<Value>& info); 122 const PropertyCallbackInfo<Value>& info);
123 static void GetHost(Local<String> name, 123 static void GetHost(Local<String> name,
124 const PropertyCallbackInfo<Value>& info); 124 const PropertyCallbackInfo<Value>& info);
125 static void GetUserAgent(Local<String> name, 125 static void GetUserAgent(Local<String> name,
126 const PropertyCallbackInfo<Value>& info); 126 const PropertyCallbackInfo<Value>& info);
127 127
128 // Callbacks that access maps 128 // Callbacks that access maps
129 static void MapGet(Local<Name> name, const PropertyCallbackInfo<Value>& info); 129 static void MapGet(Local<Name> name, const PropertyCallbackInfo<Value>& info);
130 static void MapSet(Local<Name> name, Local<Value> value, 130 static void MapSet(Local<Name> name, Local<Value> value,
131 const PropertyCallbackInfo<Value>& info); 131 const PropertyCallbackInfo<Value>& info);
132 132
133 // Utility methods for wrapping C++ objects as JavaScript objects, 133 // Utility methods for wrapping C++ objects as JavaScript objects,
134 // and going back again. 134 // and going back again.
135 Handle<Object> WrapMap(map<string, string>* obj); 135 Local<Object> WrapMap(map<string, string>* obj);
136 static map<string, string>* UnwrapMap(Handle<Object> obj); 136 static map<string, string>* UnwrapMap(Local<Object> obj);
137 Handle<Object> WrapRequest(HttpRequest* obj); 137 Local<Object> WrapRequest(HttpRequest* obj);
138 static HttpRequest* UnwrapRequest(Handle<Object> obj); 138 static HttpRequest* UnwrapRequest(Local<Object> obj);
139 139
140 Isolate* GetIsolate() { return isolate_; } 140 Isolate* GetIsolate() { return isolate_; }
141 141
142 Isolate* isolate_; 142 Isolate* isolate_;
143 Handle<String> script_; 143 Local<String> script_;
144 Persistent<Context> context_; 144 Global<Context> context_;
145 Persistent<Function> process_; 145 Global<Function> process_;
146 static Persistent<ObjectTemplate> request_template_; 146 static Global<ObjectTemplate> request_template_;
147 static Persistent<ObjectTemplate> map_template_; 147 static Global<ObjectTemplate> map_template_;
148 }; 148 };
149 149
150 150
151 // ------------------------- 151 // -------------------------
152 // --- P r o c e s s o r --- 152 // --- P r o c e s s o r ---
153 // ------------------------- 153 // -------------------------
154 154
155 155
156 static void LogCallback(const v8::FunctionCallbackInfo<v8::Value>& args) { 156 static void LogCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
157 if (args.Length() < 1) return; 157 if (args.Length() < 1) return;
158 HandleScope scope(args.GetIsolate()); 158 HandleScope scope(args.GetIsolate());
159 Handle<Value> arg = args[0]; 159 Local<Value> arg = args[0];
160 String::Utf8Value value(arg); 160 String::Utf8Value value(arg);
161 HttpRequestProcessor::Log(*value); 161 HttpRequestProcessor::Log(*value);
162 } 162 }
163 163
164 164
165 // Execute the script and fetch the Process method. 165 // Execute the script and fetch the Process method.
166 bool JsHttpRequestProcessor::Initialize(map<string, string>* opts, 166 bool JsHttpRequestProcessor::Initialize(map<string, string>* opts,
167 map<string, string>* output) { 167 map<string, string>* output) {
168 // Create a handle scope to hold the temporary references. 168 // Create a handle scope to hold the temporary references.
169 HandleScope handle_scope(GetIsolate()); 169 HandleScope handle_scope(GetIsolate());
170 170
171 // Create a template for the global object where we set the 171 // Create a template for the global object where we set the
172 // built-in global functions. 172 // built-in global functions.
173 Handle<ObjectTemplate> global = ObjectTemplate::New(GetIsolate()); 173 Local<ObjectTemplate> global = ObjectTemplate::New(GetIsolate());
174 global->Set(String::NewFromUtf8(GetIsolate(), "log"), 174 global->Set(String::NewFromUtf8(GetIsolate(), "log", NewStringType::kNormal)
175 .ToLocalChecked(),
175 FunctionTemplate::New(GetIsolate(), LogCallback)); 176 FunctionTemplate::New(GetIsolate(), LogCallback));
176 177
177 // Each processor gets its own context so different processors don't 178 // Each processor gets its own context so different processors don't
178 // affect each other. Context::New returns a persistent handle which 179 // affect each other. Context::New returns a persistent handle which
179 // is what we need for the reference to remain after we return from 180 // is what we need for the reference to remain after we return from
180 // this method. That persistent handle has to be disposed in the 181 // this method. That persistent handle has to be disposed in the
181 // destructor. 182 // destructor.
182 v8::Handle<v8::Context> context = Context::New(GetIsolate(), NULL, global); 183 v8::Local<v8::Context> context = Context::New(GetIsolate(), NULL, global);
183 context_.Reset(GetIsolate(), context); 184 context_.Reset(GetIsolate(), context);
184 185
185 // Enter the new context so all the following operations take place 186 // Enter the new context so all the following operations take place
186 // within it. 187 // within it.
187 Context::Scope context_scope(context); 188 Context::Scope context_scope(context);
188 189
189 // Make the options mapping available within the context 190 // Make the options mapping available within the context
190 if (!InstallMaps(opts, output)) 191 if (!InstallMaps(opts, output))
191 return false; 192 return false;
192 193
193 // Compile and run the script 194 // Compile and run the script
194 if (!ExecuteScript(script_)) 195 if (!ExecuteScript(script_))
195 return false; 196 return false;
196 197
197 // The script compiled and ran correctly. Now we fetch out the 198 // The script compiled and ran correctly. Now we fetch out the
198 // Process function from the global object. 199 // Process function from the global object.
199 Handle<String> process_name = String::NewFromUtf8(GetIsolate(), "Process"); 200 Local<String> process_name =
200 Handle<Value> process_val = context->Global()->Get(process_name); 201 String::NewFromUtf8(GetIsolate(), "Process", NewStringType::kNormal)
201 202 .ToLocalChecked();
203 Local<Value> process_val;
202 // If there is no Process function, or if it is not a function, 204 // If there is no Process function, or if it is not a function,
203 // bail out 205 // bail out
204 if (!process_val->IsFunction()) return false; 206 if (!context->Global()->Get(context, process_name).ToLocal(&process_val) ||
207 !process_val->IsFunction()) {
208 return false;
209 }
205 210
206 // It is a function; cast it to a Function 211 // It is a function; cast it to a Function
207 Handle<Function> process_fun = Handle<Function>::Cast(process_val); 212 Local<Function> process_fun = Local<Function>::Cast(process_val);
208 213
209 // Store the function in a Persistent handle, since we also want 214 // Store the function in a Global handle, since we also want
210 // that to remain after this call returns 215 // that to remain after this call returns
211 process_.Reset(GetIsolate(), process_fun); 216 process_.Reset(GetIsolate(), process_fun);
212 217
213 // All done; all went well 218 // All done; all went well
214 return true; 219 return true;
215 } 220 }
216 221
217 222
218 bool JsHttpRequestProcessor::ExecuteScript(Handle<String> script) { 223 bool JsHttpRequestProcessor::ExecuteScript(Local<String> script) {
219 HandleScope handle_scope(GetIsolate()); 224 HandleScope handle_scope(GetIsolate());
220 225
221 // We're just about to compile the script; set up an error handler to 226 // We're just about to compile the script; set up an error handler to
222 // catch any exceptions the script might throw. 227 // catch any exceptions the script might throw.
223 TryCatch try_catch(GetIsolate()); 228 TryCatch try_catch(GetIsolate());
224 229
230 Local<Context> context(GetIsolate()->GetCurrentContext());
231
225 // Compile the script and check for errors. 232 // Compile the script and check for errors.
226 Handle<Script> compiled_script = Script::Compile(script); 233 Local<Script> compiled_script;
227 if (compiled_script.IsEmpty()) { 234 if (!Script::Compile(context, script).ToLocal(&compiled_script)) {
228 String::Utf8Value error(try_catch.Exception()); 235 String::Utf8Value error(try_catch.Exception());
229 Log(*error); 236 Log(*error);
230 // The script failed to compile; bail out. 237 // The script failed to compile; bail out.
231 return false; 238 return false;
232 } 239 }
233 240
234 // Run the script! 241 // Run the script!
235 Handle<Value> result = compiled_script->Run(); 242 Local<Value> result;
236 if (result.IsEmpty()) { 243 if (!compiled_script->Run(context).ToLocal(&result)) {
237 // The TryCatch above is still in effect and will have caught the error. 244 // The TryCatch above is still in effect and will have caught the error.
238 String::Utf8Value error(try_catch.Exception()); 245 String::Utf8Value error(try_catch.Exception());
239 Log(*error); 246 Log(*error);
240 // Running the script failed; bail out. 247 // Running the script failed; bail out.
241 return false; 248 return false;
242 } 249 }
243 return true; 250 return true;
244 } 251 }
245 252
246 253
247 bool JsHttpRequestProcessor::InstallMaps(map<string, string>* opts, 254 bool JsHttpRequestProcessor::InstallMaps(map<string, string>* opts,
248 map<string, string>* output) { 255 map<string, string>* output) {
249 HandleScope handle_scope(GetIsolate()); 256 HandleScope handle_scope(GetIsolate());
250 257
251 // Wrap the map object in a JavaScript wrapper 258 // Wrap the map object in a JavaScript wrapper
252 Handle<Object> opts_obj = WrapMap(opts); 259 Local<Object> opts_obj = WrapMap(opts);
253 260
254 v8::Local<v8::Context> context = 261 v8::Local<v8::Context> context =
255 v8::Local<v8::Context>::New(GetIsolate(), context_); 262 v8::Local<v8::Context>::New(GetIsolate(), context_);
256 263
257 // Set the options object as a property on the global object. 264 // Set the options object as a property on the global object.
258 context->Global()->Set(String::NewFromUtf8(GetIsolate(), "options"), 265 context->Global()
259 opts_obj); 266 ->Set(context,
267 String::NewFromUtf8(GetIsolate(), "options", NewStringType::kNormal)
268 .ToLocalChecked(),
269 opts_obj)
270 .FromJust();
260 271
261 Handle<Object> output_obj = WrapMap(output); 272 Local<Object> output_obj = WrapMap(output);
262 context->Global()->Set(String::NewFromUtf8(GetIsolate(), "output"), 273 context->Global()
263 output_obj); 274 ->Set(context,
275 String::NewFromUtf8(GetIsolate(), "output", NewStringType::kNormal)
276 .ToLocalChecked(),
277 output_obj)
278 .FromJust();
264 279
265 return true; 280 return true;
266 } 281 }
267 282
268 283
269 bool JsHttpRequestProcessor::Process(HttpRequest* request) { 284 bool JsHttpRequestProcessor::Process(HttpRequest* request) {
270 // Create a handle scope to keep the temporary object references. 285 // Create a handle scope to keep the temporary object references.
271 HandleScope handle_scope(GetIsolate()); 286 HandleScope handle_scope(GetIsolate());
272 287
273 v8::Local<v8::Context> context = 288 v8::Local<v8::Context> context =
274 v8::Local<v8::Context>::New(GetIsolate(), context_); 289 v8::Local<v8::Context>::New(GetIsolate(), context_);
275 290
276 // Enter this processor's context so all the remaining operations 291 // Enter this processor's context so all the remaining operations
277 // take place there 292 // take place there
278 Context::Scope context_scope(context); 293 Context::Scope context_scope(context);
279 294
280 // Wrap the C++ request object in a JavaScript wrapper 295 // Wrap the C++ request object in a JavaScript wrapper
281 Handle<Object> request_obj = WrapRequest(request); 296 Local<Object> request_obj = WrapRequest(request);
282 297
283 // Set up an exception handler before calling the Process function 298 // Set up an exception handler before calling the Process function
284 TryCatch try_catch(GetIsolate()); 299 TryCatch try_catch(GetIsolate());
285 300
286 // Invoke the process function, giving the global object as 'this' 301 // Invoke the process function, giving the global object as 'this'
287 // and one argument, the request. 302 // and one argument, the request.
288 const int argc = 1; 303 const int argc = 1;
289 Handle<Value> argv[argc] = { request_obj }; 304 Local<Value> argv[argc] = {request_obj};
290 v8::Local<v8::Function> process = 305 v8::Local<v8::Function> process =
291 v8::Local<v8::Function>::New(GetIsolate(), process_); 306 v8::Local<v8::Function>::New(GetIsolate(), process_);
292 Handle<Value> result = process->Call(context->Global(), argc, argv); 307 Local<Value> result;
293 if (result.IsEmpty()) { 308 if (!process->Call(context, context->Global(), argc, argv).ToLocal(&result)) {
294 String::Utf8Value error(try_catch.Exception()); 309 String::Utf8Value error(try_catch.Exception());
295 Log(*error); 310 Log(*error);
296 return false; 311 return false;
297 } else { 312 } else {
298 return true; 313 return true;
299 } 314 }
300 } 315 }
301 316
302 317
303 JsHttpRequestProcessor::~JsHttpRequestProcessor() { 318 JsHttpRequestProcessor::~JsHttpRequestProcessor() {
304 // Dispose the persistent handles. When noone else has any 319 // Dispose the persistent handles. When noone else has any
305 // references to the objects stored in the handles they will be 320 // references to the objects stored in the handles they will be
306 // automatically reclaimed. 321 // automatically reclaimed.
307 context_.Reset(); 322 context_.Reset();
308 process_.Reset(); 323 process_.Reset();
309 } 324 }
310 325
311 326
312 Persistent<ObjectTemplate> JsHttpRequestProcessor::request_template_; 327 Global<ObjectTemplate> JsHttpRequestProcessor::request_template_;
313 Persistent<ObjectTemplate> JsHttpRequestProcessor::map_template_; 328 Global<ObjectTemplate> JsHttpRequestProcessor::map_template_;
314 329
315 330
316 // ----------------------------------- 331 // -----------------------------------
317 // --- A c c e s s i n g M a p s --- 332 // --- A c c e s s i n g M a p s ---
318 // ----------------------------------- 333 // -----------------------------------
319 334
320 // Utility function that wraps a C++ http request object in a 335 // Utility function that wraps a C++ http request object in a
321 // JavaScript object. 336 // JavaScript object.
322 Handle<Object> JsHttpRequestProcessor::WrapMap(map<string, string>* obj) { 337 Local<Object> JsHttpRequestProcessor::WrapMap(map<string, string>* obj) {
323 // Handle scope for temporary handles. 338 // Local scope for temporary handles.
324 EscapableHandleScope handle_scope(GetIsolate()); 339 EscapableHandleScope handle_scope(GetIsolate());
325 340
326 // Fetch the template for creating JavaScript map wrappers. 341 // Fetch the template for creating JavaScript map wrappers.
327 // It only has to be created once, which we do on demand. 342 // It only has to be created once, which we do on demand.
328 if (map_template_.IsEmpty()) { 343 if (map_template_.IsEmpty()) {
329 Handle<ObjectTemplate> raw_template = MakeMapTemplate(GetIsolate()); 344 Local<ObjectTemplate> raw_template = MakeMapTemplate(GetIsolate());
330 map_template_.Reset(GetIsolate(), raw_template); 345 map_template_.Reset(GetIsolate(), raw_template);
331 } 346 }
332 Handle<ObjectTemplate> templ = 347 Local<ObjectTemplate> templ =
333 Local<ObjectTemplate>::New(GetIsolate(), map_template_); 348 Local<ObjectTemplate>::New(GetIsolate(), map_template_);
334 349
335 // Create an empty map wrapper. 350 // Create an empty map wrapper.
336 Local<Object> result = templ->NewInstance(); 351 Local<Object> result =
352 templ->NewInstance(GetIsolate()->GetCurrentContext()).ToLocalChecked();
337 353
338 // Wrap the raw C++ pointer in an External so it can be referenced 354 // Wrap the raw C++ pointer in an External so it can be referenced
339 // from within JavaScript. 355 // from within JavaScript.
340 Handle<External> map_ptr = External::New(GetIsolate(), obj); 356 Local<External> map_ptr = External::New(GetIsolate(), obj);
341 357
342 // Store the map pointer in the JavaScript wrapper. 358 // Store the map pointer in the JavaScript wrapper.
343 result->SetInternalField(0, map_ptr); 359 result->SetInternalField(0, map_ptr);
344 360
345 // Return the result through the current handle scope. Since each 361 // Return the result through the current handle scope. Since each
346 // of these handles will go away when the handle scope is deleted 362 // of these handles will go away when the handle scope is deleted
347 // we need to call Close to let one, the result, escape into the 363 // we need to call Close to let one, the result, escape into the
348 // outer handle scope. 364 // outer handle scope.
349 return handle_scope.Escape(result); 365 return handle_scope.Escape(result);
350 } 366 }
351 367
352 368
353 // Utility function that extracts the C++ map pointer from a wrapper 369 // Utility function that extracts the C++ map pointer from a wrapper
354 // object. 370 // object.
355 map<string, string>* JsHttpRequestProcessor::UnwrapMap(Handle<Object> obj) { 371 map<string, string>* JsHttpRequestProcessor::UnwrapMap(Local<Object> obj) {
356 Handle<External> field = Handle<External>::Cast(obj->GetInternalField(0)); 372 Local<External> field = Local<External>::Cast(obj->GetInternalField(0));
357 void* ptr = field->Value(); 373 void* ptr = field->Value();
358 return static_cast<map<string, string>*>(ptr); 374 return static_cast<map<string, string>*>(ptr);
359 } 375 }
360 376
361 377
362 // Convert a JavaScript string to a std::string. To not bother too 378 // Convert a JavaScript string to a std::string. To not bother too
363 // much with string encodings we just use ascii. 379 // much with string encodings we just use ascii.
364 string ObjectToString(Local<Value> value) { 380 string ObjectToString(Local<Value> value) {
365 String::Utf8Value utf8_value(value); 381 String::Utf8Value utf8_value(value);
366 return string(*utf8_value); 382 return string(*utf8_value);
(...skipping 11 matching lines...) Expand all
378 string key = ObjectToString(Local<String>::Cast(name)); 394 string key = ObjectToString(Local<String>::Cast(name));
379 395
380 // Look up the value if it exists using the standard STL ideom. 396 // Look up the value if it exists using the standard STL ideom.
381 map<string, string>::iterator iter = obj->find(key); 397 map<string, string>::iterator iter = obj->find(key);
382 398
383 // If the key is not present return an empty handle as signal 399 // If the key is not present return an empty handle as signal
384 if (iter == obj->end()) return; 400 if (iter == obj->end()) return;
385 401
386 // Otherwise fetch the value and wrap it in a JavaScript string 402 // Otherwise fetch the value and wrap it in a JavaScript string
387 const string& value = (*iter).second; 403 const string& value = (*iter).second;
388 info.GetReturnValue().Set(String::NewFromUtf8( 404 info.GetReturnValue().Set(
389 info.GetIsolate(), value.c_str(), String::kNormalString, 405 String::NewFromUtf8(info.GetIsolate(), value.c_str(),
390 static_cast<int>(value.length()))); 406 NewStringType::kNormal,
407 static_cast<int>(value.length())).ToLocalChecked());
391 } 408 }
392 409
393 410
394 void JsHttpRequestProcessor::MapSet(Local<Name> name, Local<Value> value_obj, 411 void JsHttpRequestProcessor::MapSet(Local<Name> name, Local<Value> value_obj,
395 const PropertyCallbackInfo<Value>& info) { 412 const PropertyCallbackInfo<Value>& info) {
396 if (name->IsSymbol()) return; 413 if (name->IsSymbol()) return;
397 414
398 // Fetch the map wrapped by this object. 415 // Fetch the map wrapped by this object.
399 map<string, string>* obj = UnwrapMap(info.Holder()); 416 map<string, string>* obj = UnwrapMap(info.Holder());
400 417
401 // Convert the key and value to std::strings. 418 // Convert the key and value to std::strings.
402 string key = ObjectToString(Local<String>::Cast(name)); 419 string key = ObjectToString(Local<String>::Cast(name));
403 string value = ObjectToString(value_obj); 420 string value = ObjectToString(value_obj);
404 421
405 // Update the map. 422 // Update the map.
406 (*obj)[key] = value; 423 (*obj)[key] = value;
407 424
408 // Return the value; any non-empty handle will work. 425 // Return the value; any non-empty handle will work.
409 info.GetReturnValue().Set(value_obj); 426 info.GetReturnValue().Set(value_obj);
410 } 427 }
411 428
412 429
413 Handle<ObjectTemplate> JsHttpRequestProcessor::MakeMapTemplate( 430 Local<ObjectTemplate> JsHttpRequestProcessor::MakeMapTemplate(
414 Isolate* isolate) { 431 Isolate* isolate) {
415 EscapableHandleScope handle_scope(isolate); 432 EscapableHandleScope handle_scope(isolate);
416 433
417 Local<ObjectTemplate> result = ObjectTemplate::New(isolate); 434 Local<ObjectTemplate> result = ObjectTemplate::New(isolate);
418 result->SetInternalFieldCount(1); 435 result->SetInternalFieldCount(1);
419 result->SetHandler(NamedPropertyHandlerConfiguration(MapGet, MapSet)); 436 result->SetHandler(NamedPropertyHandlerConfiguration(MapGet, MapSet));
420 437
421 // Again, return the result through the current handle scope. 438 // Again, return the result through the current handle scope.
422 return handle_scope.Escape(result); 439 return handle_scope.Escape(result);
423 } 440 }
424 441
425 442
426 // ------------------------------------------- 443 // -------------------------------------------
427 // --- A c c e s s i n g R e q u e s t s --- 444 // --- A c c e s s i n g R e q u e s t s ---
428 // ------------------------------------------- 445 // -------------------------------------------
429 446
430 /** 447 /**
431 * Utility function that wraps a C++ http request object in a 448 * Utility function that wraps a C++ http request object in a
432 * JavaScript object. 449 * JavaScript object.
433 */ 450 */
434 Handle<Object> JsHttpRequestProcessor::WrapRequest(HttpRequest* request) { 451 Local<Object> JsHttpRequestProcessor::WrapRequest(HttpRequest* request) {
435 // Handle scope for temporary handles. 452 // Local scope for temporary handles.
436 EscapableHandleScope handle_scope(GetIsolate()); 453 EscapableHandleScope handle_scope(GetIsolate());
437 454
438 // Fetch the template for creating JavaScript http request wrappers. 455 // Fetch the template for creating JavaScript http request wrappers.
439 // It only has to be created once, which we do on demand. 456 // It only has to be created once, which we do on demand.
440 if (request_template_.IsEmpty()) { 457 if (request_template_.IsEmpty()) {
441 Handle<ObjectTemplate> raw_template = MakeRequestTemplate(GetIsolate()); 458 Local<ObjectTemplate> raw_template = MakeRequestTemplate(GetIsolate());
442 request_template_.Reset(GetIsolate(), raw_template); 459 request_template_.Reset(GetIsolate(), raw_template);
443 } 460 }
444 Handle<ObjectTemplate> templ = 461 Local<ObjectTemplate> templ =
445 Local<ObjectTemplate>::New(GetIsolate(), request_template_); 462 Local<ObjectTemplate>::New(GetIsolate(), request_template_);
446 463
447 // Create an empty http request wrapper. 464 // Create an empty http request wrapper.
448 Local<Object> result = templ->NewInstance(); 465 Local<Object> result =
466 templ->NewInstance(GetIsolate()->GetCurrentContext()).ToLocalChecked();
449 467
450 // Wrap the raw C++ pointer in an External so it can be referenced 468 // Wrap the raw C++ pointer in an External so it can be referenced
451 // from within JavaScript. 469 // from within JavaScript.
452 Handle<External> request_ptr = External::New(GetIsolate(), request); 470 Local<External> request_ptr = External::New(GetIsolate(), request);
453 471
454 // Store the request pointer in the JavaScript wrapper. 472 // Store the request pointer in the JavaScript wrapper.
455 result->SetInternalField(0, request_ptr); 473 result->SetInternalField(0, request_ptr);
456 474
457 // Return the result through the current handle scope. Since each 475 // Return the result through the current handle scope. Since each
458 // of these handles will go away when the handle scope is deleted 476 // of these handles will go away when the handle scope is deleted
459 // we need to call Close to let one, the result, escape into the 477 // we need to call Close to let one, the result, escape into the
460 // outer handle scope. 478 // outer handle scope.
461 return handle_scope.Escape(result); 479 return handle_scope.Escape(result);
462 } 480 }
463 481
464 482
465 /** 483 /**
466 * Utility function that extracts the C++ http request object from a 484 * Utility function that extracts the C++ http request object from a
467 * wrapper object. 485 * wrapper object.
468 */ 486 */
469 HttpRequest* JsHttpRequestProcessor::UnwrapRequest(Handle<Object> obj) { 487 HttpRequest* JsHttpRequestProcessor::UnwrapRequest(Local<Object> obj) {
470 Handle<External> field = Handle<External>::Cast(obj->GetInternalField(0)); 488 Local<External> field = Local<External>::Cast(obj->GetInternalField(0));
471 void* ptr = field->Value(); 489 void* ptr = field->Value();
472 return static_cast<HttpRequest*>(ptr); 490 return static_cast<HttpRequest*>(ptr);
473 } 491 }
474 492
475 493
476 void JsHttpRequestProcessor::GetPath(Local<String> name, 494 void JsHttpRequestProcessor::GetPath(Local<String> name,
477 const PropertyCallbackInfo<Value>& info) { 495 const PropertyCallbackInfo<Value>& info) {
478 // Extract the C++ request object from the JavaScript wrapper. 496 // Extract the C++ request object from the JavaScript wrapper.
479 HttpRequest* request = UnwrapRequest(info.Holder()); 497 HttpRequest* request = UnwrapRequest(info.Holder());
480 498
481 // Fetch the path. 499 // Fetch the path.
482 const string& path = request->Path(); 500 const string& path = request->Path();
483 501
484 // Wrap the result in a JavaScript string and return it. 502 // Wrap the result in a JavaScript string and return it.
485 info.GetReturnValue().Set(String::NewFromUtf8( 503 info.GetReturnValue().Set(
486 info.GetIsolate(), path.c_str(), String::kNormalString, 504 String::NewFromUtf8(info.GetIsolate(), path.c_str(),
487 static_cast<int>(path.length()))); 505 NewStringType::kNormal,
506 static_cast<int>(path.length())).ToLocalChecked());
488 } 507 }
489 508
490 509
491 void JsHttpRequestProcessor::GetReferrer( 510 void JsHttpRequestProcessor::GetReferrer(
492 Local<String> name, 511 Local<String> name,
493 const PropertyCallbackInfo<Value>& info) { 512 const PropertyCallbackInfo<Value>& info) {
494 HttpRequest* request = UnwrapRequest(info.Holder()); 513 HttpRequest* request = UnwrapRequest(info.Holder());
495 const string& path = request->Referrer(); 514 const string& path = request->Referrer();
496 info.GetReturnValue().Set(String::NewFromUtf8( 515 info.GetReturnValue().Set(
497 info.GetIsolate(), path.c_str(), String::kNormalString, 516 String::NewFromUtf8(info.GetIsolate(), path.c_str(),
498 static_cast<int>(path.length()))); 517 NewStringType::kNormal,
518 static_cast<int>(path.length())).ToLocalChecked());
499 } 519 }
500 520
501 521
502 void JsHttpRequestProcessor::GetHost(Local<String> name, 522 void JsHttpRequestProcessor::GetHost(Local<String> name,
503 const PropertyCallbackInfo<Value>& info) { 523 const PropertyCallbackInfo<Value>& info) {
504 HttpRequest* request = UnwrapRequest(info.Holder()); 524 HttpRequest* request = UnwrapRequest(info.Holder());
505 const string& path = request->Host(); 525 const string& path = request->Host();
506 info.GetReturnValue().Set(String::NewFromUtf8( 526 info.GetReturnValue().Set(
507 info.GetIsolate(), path.c_str(), String::kNormalString, 527 String::NewFromUtf8(info.GetIsolate(), path.c_str(),
508 static_cast<int>(path.length()))); 528 NewStringType::kNormal,
529 static_cast<int>(path.length())).ToLocalChecked());
509 } 530 }
510 531
511 532
512 void JsHttpRequestProcessor::GetUserAgent( 533 void JsHttpRequestProcessor::GetUserAgent(
513 Local<String> name, 534 Local<String> name,
514 const PropertyCallbackInfo<Value>& info) { 535 const PropertyCallbackInfo<Value>& info) {
515 HttpRequest* request = UnwrapRequest(info.Holder()); 536 HttpRequest* request = UnwrapRequest(info.Holder());
516 const string& path = request->UserAgent(); 537 const string& path = request->UserAgent();
517 info.GetReturnValue().Set(String::NewFromUtf8( 538 info.GetReturnValue().Set(
518 info.GetIsolate(), path.c_str(), String::kNormalString, 539 String::NewFromUtf8(info.GetIsolate(), path.c_str(),
519 static_cast<int>(path.length()))); 540 NewStringType::kNormal,
541 static_cast<int>(path.length())).ToLocalChecked());
520 } 542 }
521 543
522 544
523 Handle<ObjectTemplate> JsHttpRequestProcessor::MakeRequestTemplate( 545 Local<ObjectTemplate> JsHttpRequestProcessor::MakeRequestTemplate(
524 Isolate* isolate) { 546 Isolate* isolate) {
525 EscapableHandleScope handle_scope(isolate); 547 EscapableHandleScope handle_scope(isolate);
526 548
527 Local<ObjectTemplate> result = ObjectTemplate::New(isolate); 549 Local<ObjectTemplate> result = ObjectTemplate::New(isolate);
528 result->SetInternalFieldCount(1); 550 result->SetInternalFieldCount(1);
529 551
530 // Add accessors for each of the fields of the request. 552 // Add accessors for each of the fields of the request.
531 result->SetAccessor( 553 result->SetAccessor(
532 String::NewFromUtf8(isolate, "path", String::kInternalizedString), 554 String::NewFromUtf8(isolate, "path", NewStringType::kInternalized)
555 .ToLocalChecked(),
533 GetPath); 556 GetPath);
534 result->SetAccessor( 557 result->SetAccessor(
535 String::NewFromUtf8(isolate, "referrer", String::kInternalizedString), 558 String::NewFromUtf8(isolate, "referrer", NewStringType::kInternalized)
559 .ToLocalChecked(),
536 GetReferrer); 560 GetReferrer);
537 result->SetAccessor( 561 result->SetAccessor(
538 String::NewFromUtf8(isolate, "host", String::kInternalizedString), 562 String::NewFromUtf8(isolate, "host", NewStringType::kInternalized)
563 .ToLocalChecked(),
539 GetHost); 564 GetHost);
540 result->SetAccessor( 565 result->SetAccessor(
541 String::NewFromUtf8(isolate, "userAgent", String::kInternalizedString), 566 String::NewFromUtf8(isolate, "userAgent", NewStringType::kInternalized)
567 .ToLocalChecked(),
542 GetUserAgent); 568 GetUserAgent);
543 569
544 // Again, return the result through the current handle scope. 570 // Again, return the result through the current handle scope.
545 return handle_scope.Escape(result); 571 return handle_scope.Escape(result);
546 } 572 }
547 573
548 574
549 // --- Test --- 575 // --- Test ---
550 576
551 577
(...skipping 45 matching lines...) Expand 10 before | Expand all | Expand 10 after
597 } else { 623 } else {
598 string key = arg.substr(0, index); 624 string key = arg.substr(0, index);
599 string value = arg.substr(index+1); 625 string value = arg.substr(index+1);
600 (*options)[key] = value; 626 (*options)[key] = value;
601 } 627 }
602 } 628 }
603 } 629 }
604 630
605 631
606 // Reads a file into a v8 string. 632 // Reads a file into a v8 string.
607 Handle<String> ReadFile(Isolate* isolate, const string& name) { 633 MaybeLocal<String> ReadFile(Isolate* isolate, const string& name) {
608 FILE* file = fopen(name.c_str(), "rb"); 634 FILE* file = fopen(name.c_str(), "rb");
609 if (file == NULL) return Handle<String>(); 635 if (file == NULL) return MaybeLocal<String>();
610 636
611 fseek(file, 0, SEEK_END); 637 fseek(file, 0, SEEK_END);
612 size_t size = ftell(file); 638 size_t size = ftell(file);
613 rewind(file); 639 rewind(file);
614 640
615 char* chars = new char[size + 1]; 641 char* chars = new char[size + 1];
616 chars[size] = '\0'; 642 chars[size] = '\0';
617 for (size_t i = 0; i < size;) { 643 for (size_t i = 0; i < size;) {
618 i += fread(&chars[i], 1, size - i, file); 644 i += fread(&chars[i], 1, size - i, file);
619 if (ferror(file)) { 645 if (ferror(file)) {
620 fclose(file); 646 fclose(file);
621 return Handle<String>(); 647 return MaybeLocal<String>();
622 } 648 }
623 } 649 }
624 fclose(file); 650 fclose(file);
625 Handle<String> result = String::NewFromUtf8( 651 MaybeLocal<String> result = String::NewFromUtf8(
626 isolate, chars, String::kNormalString, static_cast<int>(size)); 652 isolate, chars, NewStringType::kNormal, static_cast<int>(size));
627 delete[] chars; 653 delete[] chars;
628 return result; 654 return result;
629 } 655 }
630 656
631 657
632 const int kSampleSize = 6; 658 const int kSampleSize = 6;
633 StringHttpRequest kSampleRequests[kSampleSize] = { 659 StringHttpRequest kSampleRequests[kSampleSize] = {
634 StringHttpRequest("/process.cc", "localhost", "google.com", "firefox"), 660 StringHttpRequest("/process.cc", "localhost", "google.com", "firefox"),
635 StringHttpRequest("/", "localhost", "google.net", "firefox"), 661 StringHttpRequest("/", "localhost", "google.net", "firefox"),
636 StringHttpRequest("/", "localhost", "google.org", "safari"), 662 StringHttpRequest("/", "localhost", "google.org", "safari"),
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after
669 if (file.empty()) { 695 if (file.empty()) {
670 fprintf(stderr, "No script was specified.\n"); 696 fprintf(stderr, "No script was specified.\n");
671 return 1; 697 return 1;
672 } 698 }
673 ArrayBufferAllocator array_buffer_allocator; 699 ArrayBufferAllocator array_buffer_allocator;
674 Isolate::CreateParams create_params; 700 Isolate::CreateParams create_params;
675 create_params.array_buffer_allocator = &array_buffer_allocator; 701 create_params.array_buffer_allocator = &array_buffer_allocator;
676 Isolate* isolate = Isolate::New(create_params); 702 Isolate* isolate = Isolate::New(create_params);
677 Isolate::Scope isolate_scope(isolate); 703 Isolate::Scope isolate_scope(isolate);
678 HandleScope scope(isolate); 704 HandleScope scope(isolate);
679 Handle<String> source = ReadFile(isolate, file); 705 Local<String> source;
680 if (source.IsEmpty()) { 706 if (!ReadFile(isolate, file).ToLocal(&source)) {
681 fprintf(stderr, "Error reading '%s'.\n", file.c_str()); 707 fprintf(stderr, "Error reading '%s'.\n", file.c_str());
682 return 1; 708 return 1;
683 } 709 }
684 JsHttpRequestProcessor processor(isolate, source); 710 JsHttpRequestProcessor processor(isolate, source);
685 map<string, string> output; 711 map<string, string> output;
686 if (!processor.Initialize(&options, &output)) { 712 if (!processor.Initialize(&options, &output)) {
687 fprintf(stderr, "Error initializing processor.\n"); 713 fprintf(stderr, "Error initializing processor.\n");
688 return 1; 714 return 1;
689 } 715 }
690 if (!ProcessEntries(&processor, kSampleSize, kSampleRequests)) 716 if (!ProcessEntries(&processor, kSampleSize, kSampleRequests))
691 return 1; 717 return 1;
692 PrintMap(&output); 718 PrintMap(&output);
693 } 719 }
OLDNEW
« no previous file with comments | « samples/hello-world.cc ('k') | samples/samples.gyp » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698