Esempio n. 1
0
int Conv::ToJavaMap(JNIEnv *jniEnv, Handle<Value> val, int componentType, jobject *jVal) {
  Local<Object> oVal;
  Local<Array> aPropertyNames;
  if(val.IsEmpty() || val->IsNull() || val->IsUndefined()) {
    *jVal = 0;
    return OK;
  }
  if(!val->IsObject())
    return ErrorType;
  
  oVal = val->ToObject();
  aPropertyNames = oVal->GetOwnPropertyNames();
  int len = aPropertyNames->Length();

  jobject ob = jniEnv->NewObject(mapClass, mapCtor);
  if(ob) {
    int res = OK;
    for(int i = 0; i < len; i++) {
      Local<String> key = Local<String>::Cast(aPropertyNames->Get(i));
      jstring jKey; jobject item;
      res = ToJavaString(jniEnv, key, &jKey);
      if(res != OK) break;
      res = ToJavaObject(jniEnv, oVal->Get(key), componentType, &item);
      if(res != OK) break;
      jniEnv->CallObjectMethod(ob, mapPut, jKey, item);
    }
  }
  if(ob) {
    *jVal = ob;
    return OK;
  }
  if(jniEnv->ExceptionCheck())
    jniEnv->ExceptionClear();
  return ErrorVM;
}
Esempio n. 2
0
// Check if a global appmetrics agent module is already loaded.
// This is actually searching the module cache for a module with filepath
// ending .../appmetrics/launcher.js
static bool isGlobalAgentAlreadyLoaded(Handle<Object> module) {
	//Nan::HandleScope scope;
	Local<Object> cache = getRequireCache(module);
	Local<Array> props = cache->GetOwnPropertyNames();
	if (props->Length() > 0) {
		for (uint32_t i=0; i<props->Length(); i++) {
			Local<Value> entry = props->Get(i);
			if (entry->IsString() && isAppMetricsFile("launcher.js", toStdString(entry->ToString()))) {
				return true;
			}
		}
	}

	return false;
}
//delete the returned local reference after use
jobjectArray NativeScriptRuntime::GetMethodOverrides(JEnv& env, const Local<Object>& implementationObject)
{
	if (implementationObject.IsEmpty())
	{
		return JavaObjectArrayCache::GetJavaStringArray(0);
	}

	vector<jstring> methodNames;
	auto propNames = implementationObject->GetOwnPropertyNames();
	for (int i = 0; i < propNames->Length(); i++)
	{
		auto name = propNames->Get(i).As<String>();
		auto method = implementationObject->Get(name);

		bool methodFound = !method.IsEmpty() && method->IsFunction();

		if (methodFound)
		{
			String::Utf8Value stringValue(name);
			jstring value = env.NewStringUTF(*stringValue);
			methodNames.push_back(value);
		}
	}

	int methodCount = methodNames.size();

	jobjectArray methodOverrides = JavaObjectArrayCache::GetJavaStringArray(methodCount);
	for (int i = 0; i < methodCount; i++)
	{
		env.SetObjectArrayElement(methodOverrides, i, methodNames[i]);
	}

	for (int i = 0; i < methodCount; i++)
	{
		env.DeleteLocalRef(methodNames[i]);
	}

	return methodOverrides;
}
Esempio n. 4
0
		Handle<Value> evalInContext(const Arguments& args) {
			if (args.Length() < 3) {
				return ThrowException(Exception::TypeError(String::New("evalInContext takes 3 arguments.")));
			}
			
			if (!args[1]->IsObject()) {
				return ThrowException(Exception::TypeError(String::New("evalInContext expects an object as second argument.")));
			}
			
			HandleScope scope;
			
			Persistent<Context> context = Context::New();
			Context::Scope context_scope(context);

			Local<Object> global = context->Global();

			Local<Object> jscontext = args[1]->ToObject()->Clone();
			Local<Array> names = jscontext->GetOwnPropertyNames();
			for (int i = 0; i < names->Length(); i++) {
				global->Set(names->Get(i), jscontext->Get(names->Get(i)));
			}

			TryCatch tc;
			
			Local<Script> compiled = Script::Compile(args[0]->ToString(), args[2]->ToString());
			
			if (compiled.IsEmpty()) {
				return tc.ReThrow();
			}
			
			Handle<Value> value = compiled->Run();
			
			if (value.IsEmpty()) {
				return tc.ReThrow();
			}

			
			return scope.Close(value);
		}
Esempio n. 5
0
	void SerializePart(google::protobuf::Message *message, Handle<Object> src) {
		Handle<Function> to_array = handle_->GetInternalField(3).As<Function>();
		Handle<Array> properties = to_array->Call(src, 0, NULL).As<Array>();
		const Reflection *r = message->GetReflection();
		for (int i = 0; i < descriptor->field_count(); i++) {
			Local<Value> value = properties->Get(i);
			if (value->IsUndefined() || value->IsNull()) 
				continue;

			const FieldDescriptor* field = descriptor->field(i);
			if (field->is_repeated()) {
				if (value->IsArray()) {
					Handle<Array> array = value.As<Array>();
					int length = array->Length();
					for (int j = 0; j < length; j++)
						SerializeField(message, r, field, array->Get(j));
				}
				else if (value->IsObject() && 
					field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && 
					field->message_type()->name().compare(0, 20, "KeyValuePair_String_") == 0) {
					Local<Object> object = value.As<Object>();
					Local<Array> subProperties = object->GetOwnPropertyNames();
					int len = subProperties->Length();
					for (int keyIdx = 0; keyIdx < len; keyIdx++) {
						Local<Object> keyValuePair = Object::New();
						Local<Value> key = subProperties->Get(keyIdx);
						keyValuePair->Set(KeySymbol, key);
						keyValuePair->Set(ValueSymbol, object->Get(key));
						SerializeField(message, r, field, keyValuePair);
					}
				}
			} else {
				SerializeField(message, r, field, value);
			}
		}
	}
Esempio n. 6
0
void GNContext::applyOptions(Handle<Value> optsV) {
    if (!GNUtil::isDictionaryObject(optsV)) {
        return;
    }
    TryCatch try_catch;
    Local<Object> opts = optsV->ToObject();
    Local<Array> names = opts->GetOwnPropertyNames();
    // Walk the SETTERS array
    for(unsigned int i = 0; i < names->Length(); i++) {
        Local<Value> nameVal = names->Get(i);
        String::AsciiValue name(nameVal);
        Local<Value> opt = opts->Get(nameVal);
        for (size_t s = 0; s < NUM_SETTERS; ++s) {
            if (strcmp(SETTERS[s].opt_name, *name) == 0) {
                SETTERS[s].setter(context_, opt);
                break;
            }
        }
        if (try_catch.HasCaught()) {
            try_catch.ReThrow();
            return;
        }
    }
}
Handle<Value> TiHTTPClientObject::_send(void* userContext, TiObject* /*caller*/, const Arguments& args)
{
    HandleScope handleScope;
    TiHTTPClientObject* obj = (TiHTTPClientObject*) userContext;
    NativeHTTPClientObject* nhttp = (NativeHTTPClientObject*) obj->getNativeObject();

    QString data;
    if (args.Length() > 0) {
        if (args[0]->IsObject()) {
            // Convert objects into form-encoded data.
            QUrl url;
            Local<Object> formData = args[0]->ToObject();
            Local<Array> propertyNames = formData->GetOwnPropertyNames();
            uint32_t propertyCount = propertyNames->Length();
            for (uint32_t i = 0; i < propertyCount; i++) {
                Local<Value> key = propertyNames->Get(i);
                Local<Value> value = formData->Get(key);
                url.addQueryItem(QString::fromUtf8(*String::Utf8Value(key)),
                                 QString::fromUtf8(*String::Utf8Value(value)));
            }
            data = url.toString().mid(1);  // exclude the '?' character
        } else {
            data = QString::fromUtf8(*String::Utf8Value(args[0]));
        }
    }

    try
    {
        nhttp->send(data);
    }
    catch (NativeException& ne)
    {
        return ThrowException(String::New(ne.what()));
    }
    return Undefined();
}
Esempio n. 8
0
void Proxy::proxyConstructor(const v8::FunctionCallbackInfo<v8::Value>& args)
{
    LOGD(TAG, "proxy constructor callback!");
    Isolate* isolate = args.GetIsolate();
    EscapableHandleScope scope(isolate);

    JNIEnv *env = JNIScope::getEnv();
    Local<Object> jsProxy = args.This();

    // First things first, we need to wrap the object in case future calls need to unwrap proxy!
    Proxy* proxy = new Proxy(NULL);
    proxy->wrap(isolate, jsProxy);

    // every instance gets a special "_properties" object for us to use internally for get/setProperty
    jsProxy->DefineOwnProperty(isolate->GetCurrentContext(), propertiesSymbol.Get(isolate), Object::New(isolate), static_cast<PropertyAttribute>(DontEnum));

    // Now we hook up a java Object from the JVM...
    jobject javaProxy = ProxyFactory::unwrapJavaProxy(args); // do we already have one that got passed in?
    bool deleteRef = false;
    if (!javaProxy) {
        // No passed in java object, so let's create an instance
        // Look up java class from prototype...
        Local<Object> prototype = jsProxy->GetPrototype()->ToObject(isolate);
        Local<Function> constructor = prototype->Get(constructorSymbol.Get(isolate)).As<Function>();
        Local<External> wrap = constructor->Get(javaClassSymbol.Get(isolate)).As<External>();
        jclass javaClass = static_cast<jclass>(wrap->Value());

        // Now we create an instance of the class and hook it up
        JNIUtil::logClassName("Creating java proxy for class %s", javaClass);
        javaProxy = ProxyFactory::createJavaProxy(javaClass, jsProxy, args);
        deleteRef = true;
    }
    proxy->attach(javaProxy);

    int length = args.Length();

    if (length > 0 && args[0]->IsObject()) {
        bool extend = true;
        Local<Object> createProperties = args[0].As<Object>();
        Local<String> constructorName = createProperties->GetConstructorName();
        if (strcmp(*titanium::Utf8Value(constructorName), "Arguments") == 0) {
            extend = false;
            int32_t argsLength = createProperties->Get(STRING_NEW(isolate, "length"))->Int32Value();
            if (argsLength > 1) {
                Local<Value> properties = createProperties->Get(1);
                if (properties->IsObject()) {
                    extend = true;
                    createProperties = properties.As<Object>();
                }
            }
        }

        if (extend) {
            Local<Array> names = createProperties->GetOwnPropertyNames();
            int length = names->Length();
            Local<Object> properties = jsProxy->Get(propertiesSymbol.Get(isolate))->ToObject(isolate);

            for (int i = 0; i < length; ++i) {
                Local<Value> name = names->Get(i);
                Local<Value> value = createProperties->Get(name);
                bool isProperty = true;
                if (name->IsString()) {
                    Local<String> nameString = name.As<String>();
                    if (!jsProxy->HasRealNamedCallbackProperty(nameString)
                            && !jsProxy->HasRealNamedProperty(nameString)) {
                        jsProxy->Set(name, value);
                        isProperty = false;
                    }
                }
                if (isProperty) {
                    properties->Set(name, value);
                }
            }
        }
    }


    if (!args.Data().IsEmpty() && args.Data()->IsFunction()) {
        Local<Function> proxyFn = args.Data().As<Function>();
        Local<Value> *fnArgs = new Local<Value>[length];
        for (int i = 0; i < length; ++i) {
            fnArgs[i] = args[i];
        }
        proxyFn->Call(isolate->GetCurrentContext(), jsProxy, length, fnArgs);
    }

    if (deleteRef) {
        JNIEnv *env = JNIScope::getEnv();
        if (env) {
            env->DeleteLocalRef(javaProxy);
        }
    }

    args.GetReturnValue().Set(scope.Escape(jsProxy));
}
Handle<Value>
NodeSandbox::node_spawn(const Arguments& args)
{
  HandleScope scope;
  char** argv;
  std::map<std::string, std::string> envp;
  SandboxWrapper* wrap;

  wrap = node::ObjectWrap::Unwrap<SandboxWrapper>(args.This());
  argv = static_cast<char**>(calloc (sizeof (char*), args.Length()+1));
  argv[args.Length()] = nullptr;

  for(int i = 0; i < args.Length(); i++) {
    if (args[i]->IsString()) {
      Local<String> v = args[i]->ToString();
      argv[i] = static_cast<char*>(calloc(sizeof(char), v->Utf8Length()+1));
      v->WriteUtf8(argv[i]);
    } else {
      if (i <= args.Length() - 2 ) {
        ThrowException(Exception::TypeError(String::New("Arguments must be strings.")));
        goto out;
      } else {
        // Last parameter is an options structure
        Local<Object> options = args[i]->ToObject();
        if (!options.IsEmpty()) {
          if (options->HasRealNamedProperty(String::NewSymbol("env"))) {
            Local<Object> envOptions = options->Get(String::NewSymbol("env"))->ToObject();
            if (!envOptions.IsEmpty()) {
              Local<Array> envArray = envOptions->GetOwnPropertyNames();
              for (uint32_t i = 0; i < envArray->Length(); i++) {
                std::vector<char> strName;
                std::vector<char> strValue;
                Local<String> envName;
                Local<String> envValue;

                if (!(envArray->Get(i)->IsString() && envArray->Get(i)->IsString()))
                  goto err_env;

                envName = envArray->Get(i)->ToString();
                envValue = envOptions->Get(envName)->ToString();

                strName.resize (envName->Utf8Length()+1);
                strValue.resize (envValue->Utf8Length()+1);
                envName->WriteUtf8 (strName.data());
                envValue->WriteUtf8 (strValue.data());
                envp.insert (std::make_pair(std::string (strName.data()), std::string(strValue.data())));
              }
            } else {
              goto err_env;
            }
          }
        } else {
          goto err_options;
        }
      }
    }
  }

  wrap->sbox->getVFS().setCWD ("/contract/");
  wrap->sbox->spawn(argv, envp);

  goto out;

err_env:
  ThrowException(Exception::TypeError(String::New("'env' option must be a map of string:string")));
  goto out;

err_options:
  ThrowException(Exception::TypeError(String::New("Last argument must be an options structure.")));
  goto out;

out:
  for (int i = 0; i < args.Length();i ++) {
    free (argv[i]);
  }
  free (argv);

  return Undefined();
}