Beispiel #1
0
  std::shared_ptr<CameraDriverInterface> GetDevice(const Uri& uri)
  {
    std::vector<Uri> suburis = splitUri(uri.url);
    std::vector<std::shared_ptr<CameraDriverInterface>> cameras;
    cameras.reserve(suburis.size());

    for( const Uri& uri : suburis ) {
      try {
        std::cout << "Creating stream from uri: " << uri.ToString()
                  << std::endl;
        cameras.emplace_back
            (DeviceRegistry<hal::CameraDriverInterface>::I().Create(uri));
      } catch ( std::exception& e ) {
        throw DeviceException(std::string("Error creating driver from uri \"") +
                              uri.ToString() + "\": " + e.what());
      }
    }

    if( cameras.empty() ) {
      throw DeviceException("No input cameras given to join");
    }

    JoinCameraDriver* pDriver = new JoinCameraDriver(cameras);
    return std::shared_ptr<CameraDriverInterface>( pDriver );
  }
Beispiel #2
0
TESTFUNCTION void Uri_filenameTest() {
    String  fileName = "test.txt";
    Uri uri = Uri::fromAssets(fileName);

    jclogf("path = %s", uri.getPath().c_str());
    _assertTrue( strcmp( uri.getPath().c_str(), fileName.c_str() ) == 0);
}
Beispiel #3
0
bool RegexPattern::
match(Uri const& target, bool const caseSensitive/*= false*/) const
{
    if (m_disabled) return false;

    try {
        if (!m_regEx || caseSensitive != m_regExCaseSensitivity) {

            auto syntax = std::regex::ECMAScript;
            if (!caseSensitive) {
                syntax |= std::regex::icase;
            }

            m_regEx = std::make_unique<std::regex>(
                m_pattern.begin(), m_pattern.end(),
                syntax
            );

            m_regExCaseSensitivity = caseSensitive;
        }
        return std::regex_match(target.begin(), target.end(), *m_regEx);
    }
    catch (std::exception const& e) {
        std::cerr << "regex error: " << m_pattern << ":" << e.what() << "\n";
        m_disabled = true;
        return false;
    }
}
Beispiel #4
0
ProtocolHandler::ErrorCode BuiltinProtocolHandlersLocal::open(const Uri &uri, iint32 openMode)
{
    if (!d->m_opened.empty() && d->m_opened.isValid()) {
        IDEAL_DEBUG_WARNING("the uri " << d->m_opened.uri() << " was opened. Closing");
        close();
    }
    d->m_opened = uri;
    if (!uri.isValid()) {
        return InvalidURI;
    }
    iint32 oflag = 0;
    if ((openMode & Read) && (openMode & Write)) {
        oflag = O_RDWR;
    } else if (openMode & Read) {
        oflag = O_RDONLY;
    } else {
        oflag = O_WRONLY;
    }
    d->m_fd = ::open(uri.path().data(), oflag);
    if (d->m_fd > -1) {
        return NoError;
    }
    switch (errno) {
        case EACCES:
            return InsufficientPermissions;
            break;
        default:
            return UnknownError;
            break;
    }
}
Beispiel #5
0
void
GeoLocation::Run(const String& command) {
	if(!command.IsEmpty()) {
		Uri commandUri;
		commandUri.SetUri(command);
		String method = commandUri.GetHost();
		StringTokenizer strTok(commandUri.GetPath(), L"/");
		if(strTok.GetTokenCount() > 1) {
			strTok.GetNextToken(callbackId);
			AppLogDebug("Method %S, CallbackId: %S", method.GetPointer(), callbackId.GetPointer());
		}
		AppLogDebug("Method %S, Callback: %S", method.GetPointer(), callbackId.GetPointer());
		// used to determine callback ID
		if(method == L"com.phonegap.Geolocation.watchPosition" && !callbackId.IsEmpty() && !IsWatching()) {
			AppLogDebug("watching position...");
			StartWatching();
		}
		if(method == L"com.phonegap.Geolocation.stop" && IsWatching()) {
			AppLogDebug("stop watching position...");
			StopWatching();
		}
		if(method == L"com.phonegap.Geolocation.getCurrentPosition" && !callbackId.IsEmpty() && !IsWatching()) {
			AppLogDebug("getting current position...");
			GetLastKnownLocation();
		}
		AppLogDebug("GeoLocation command %S completed", command.GetPointer());
	}
}
Beispiel #6
0
void
Accelerometer::Run(const String& command) {
	if (!command.IsEmpty()) {
		Uri commandUri;
		commandUri.SetUri(command);
		String method = commandUri.GetHost();
		StringTokenizer strTok(commandUri.GetPath(), L"/");
		if(strTok.GetTokenCount() == 1) {
			strTok.GetNextToken(callbackId);
			AppLogDebug("Method %S, CallbackId: %S", method.GetPointer(), callbackId.GetPointer());
		}
		if(method == L"com.cordova.Accelerometer.watchAcceleration" && !callbackId.IsEmpty() && !IsStarted()) {
			StartSensor();
		}
		if(method == L"com.cordova.Accelerometer.clearWatch" && IsStarted()) {
			StopSensor();
		}
		if(method == L"com.cordova.Accelerometer.getCurrentAcceleration" && !callbackId.IsEmpty() && !IsStarted()) {
			GetLastAcceleration();
		}
		AppLogDebug("Acceleration command %S completed", command.GetPointer());
	} else {
		AppLogDebug("Can't run empty command");
	}
}
Beispiel #7
0
bool BuiltinProtocolHandlersHttp::Private::sendCommand(CommandType commandType, const Uri &uri)
{
    iint32 commandSize = 0;
    switch (commandType) {
        case Get:
            commandSize = strlen(m_commandGet);
            break;
        case Head:
            commandSize = strlen(m_commandHead);
            break;
    }
    commandSize += uri.host().size() + uri.path().size();
    ichar *command = (ichar*) calloc(commandSize + 1, sizeof(ichar));
    switch (commandType) {
        case Get:
            sprintf(command, "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n", uri.path().data(), uri.host().data());
            break;
        case Head:
            sprintf(command, "HEAD %s HTTP/1.1\r\nHost: %s\r\n\r\n", uri.path().data(), uri.host().data());
            break;
        default:
            IDEAL_DEBUG_WARNING("unknown command type");
            break;
    }
    const iint32 bytesSent = send(m_sockfd, command, commandSize, 0);
    free(command);
    return bytesSent == commandSize;
}
Beispiel #8
0
bool HttpParserImpl::parseUrl()
{
    Uri uri;
    if(!uri.parse(url_)) {
        return false;
    }
    const std::string& query = uri.getQuery();
    std::string::size_type pos = 0;
    while (true) {
        auto pos1 = query.find('=', pos);
        if(pos1 == std::string::npos){
            break;
        }
        std::string name(query.begin()+pos, query.begin()+pos1);
        pos = pos1 + 1;
        pos1 = query.find('&', pos);
        if(pos1 == std::string::npos){
            std::string value(query.begin()+pos, query.end());
            addParamValue(name, value);
            break;
        }
        std::string value(query.begin()+pos, query.begin()+pos1);
        pos = pos1 + 1;
        addParamValue(name, value);
    }
    
    return true;
}
Beispiel #9
0
void
DebugConsole::CleanUp(String& str) {
	Uri uri;
	uri.SetUri(str);
	str.Clear();
	str.Append(uri.ToString());
}
Beispiel #10
0
void InvocationUpnp::WriteRequest(const Uri& aUri)
{
    Sws<1024> writeBuffer(iSocket);
    WriterHttpRequest writerRequest(writeBuffer);
    Bwh body;

    try {
        Endpoint endpoint(aUri.Port(), aUri.Host());
        TUint timeout = iCpStack.Env().InitParams()->TcpConnectTimeoutMs();
        iSocket.Connect(endpoint, timeout);
    }
    catch (NetworkTimeout&) {
        iInvocation.SetError(Error::eSocket, Error::eCodeTimeout, Error::kDescriptionSocketTimeout);
        THROW(NetworkTimeout);
    }

    try {
        InvocationBodyWriter::Write(iInvocation, body);
        WriteHeaders(writerRequest, aUri, body.Bytes());
        writeBuffer.Write(body);
        writeBuffer.WriteFlush();
    }
    catch (WriterError) {
        iInvocation.SetError(Error::eHttp, Error::kCodeUnknown, Error::kDescriptionUnknown);
        THROW(WriterError);
    }
}
Beispiel #11
0
void EventUpnp::SubscribeWriteRequest(const Uri& aPublisher, const Uri& aSubscriber, TUint aDurationSecs)
{
    const Brn kRequestMethod("SUBSCRIBE");
    const Brn kMethodCallback("CALLBACK");
    const Brn kMethodNt("NT");
    const Brn kFieldNt("upnp:event");
    Sws<1024> writeBuffer(iSocket);
    WriterHttpRequest writerRequest(writeBuffer);

    writerRequest.WriteMethod(kRequestMethod, aPublisher.PathAndQuery(), Http::eHttp11);
    Http::WriteHeaderHostAndPort(writerRequest, aPublisher);

    IWriterAscii& writerField = writerRequest.WriteHeaderField(kMethodCallback);
    writerField.Write('<');
    writerField.Write(aSubscriber.AbsoluteUri());
    writerField.Write('>');
    writerField.WriteNewline();

    writerField = writerRequest.WriteHeaderField(kMethodNt);
    writerField.Write(kFieldNt);
    writerField.WriteNewline();

    WriteHeaderTimeout(writerRequest, aDurationSecs);

    writerField.WriteNewline();
    writerRequest.WriteFlush();
}
Beispiel #12
0
TBool CpiDeviceListUpnp::IsLocationReachable(const Brx& aLocation) const
{
    /* linux's filtering of multicast messages appears to be buggy and messages
       received by all interfaces are sometimes delivered to sockets which are
       bound to / members of a group on a single (different) interface.  It'd be
       more correct to filter these out in SsdpListenerMulticast but that would
       require API changes which would be more inconvenient than just moving the
       filtering here.
       This should be reconsidered if we ever add more clients of SsdpListenerMulticast */
    TBool reachable = false;
    Uri uri;
    try {
        uri.Replace(aLocation);
    }
    catch (UriError&) {
        return false;
    }
    iLock.Wait();
    Endpoint endpt(0, uri.Host());
    NetworkAdapter* nif = iCpStack.Env().NetworkAdapterList().CurrentAdapter("CpiDeviceListUpnp::IsLocationReachable");
    if (nif != NULL) {
        if (nif->Address() == iInterface && nif->ContainsAddress(endpt.Address())) {
            reachable = true;
        }
        nif->RemoveRef("CpiDeviceListUpnp::IsLocationReachable");
    }
    iLock.Signal();
    return reachable;
}
Beispiel #13
0
void
Network::Run(const String& command) {
	if (!command.IsEmpty()) {
		String args;
		String delim(L"/");
		command.SubString(String(L"gap://").GetLength(), args);
		StringTokenizer strTok(args, delim);
		if(strTok.GetTokenCount() < 3) {
			AppLogDebug("Not enough params");
			return;
		}
		String method;
		String hostAddr;
		strTok.GetNextToken(method);
		strTok.GetNextToken(callbackId);
		strTok.GetNextToken(hostAddr);

		// URL decoding
		Uri uri;
		uri.SetUri(hostAddr);
		AppLogDebug("Method %S, callbackId %S, hostAddr %S URI %S", method.GetPointer(), callbackId.GetPointer(), hostAddr.GetPointer(), uri.ToString().GetPointer());
		if(method == L"org.apache.cordova.Network.isReachable") {
			IsReachable(uri.ToString());
		}
		AppLogDebug("Network command %S completed", command.GetPointer());
		} else {
			AppLogDebug("Can't run empty command");
		}
}
Beispiel #14
0
void
BitmapImage::OnPropertyChanged (PropertyChangedEventArgs *args, MoonError *error)
{
	if (args->GetProperty ()->GetOwnerType () != Type::BITMAPIMAGE) {
		BitmapSource::OnPropertyChanged (args, error);
		return;
	}

	if (args->GetId () == BitmapImage::UriSourceProperty) {
		Uri *uri = args->GetNewValue () ? args->GetNewValue ()->AsUri () : NULL;

		Abort ();

		if (Uri::IsNullOrEmpty (uri)) {
			SetBitmapData (NULL, false);
		} else if (uri->IsInvalidPath ()) {
			if (IsBeingParsed ())
				MoonError::FillIn (error, MoonError::ARGUMENT_OUT_OF_RANGE, 0, "invalid path found in uri");
			SetBitmapData (NULL, false);
		} else {
			AddTickCall (uri_source_changed_callback);
		}
	} else if (args->GetId () == BitmapImage::ProgressProperty) {
		if (HasHandlers (DownloadProgressEvent))
			Emit (DownloadProgressEvent, new DownloadProgressEventArgs (GetProgress ()));
	}

	NotifyListenersOfPropertyChange (args, error);
}
Beispiel #15
0
void Http::WriteHeaderHostAndPort(WriterHttpHeader& aWriter, const Uri& aUri)
{
    IWriterAscii& writer = aWriter.WriteHeaderField(Http::kHeaderHost);
    writer.Write(aUri.Host());
    writer.Write(':');
    writer.WriteUint(aUri.Port());
    writer.WriteNewline();
}
Beispiel #16
0
//==============================================================================
std::string Uri::getUri(const std::string& _input)
{
  Uri uri;
  if(uri.fromStringOrPath(_input))
    return uri.toString();
  else
    return "";
}
Beispiel #17
0
//=============================================================================
bool Uri::operator!=(const Uri& v) const
{
  return get_scheme() != v.get_scheme() ||
    get_host() != v.get_host() ||
    get_port() != v.get_port() ||
    get_path() != v.get_path() ||
    get_query() != v.get_query();
}
Beispiel #18
0
//=============================================================================
bool Uri::operator==(const Uri& v) const
{
  return get_scheme() == v.get_scheme() &&
    get_host() == v.get_host() &&
    get_port() == v.get_port() &&
    get_path() == v.get_path() &&
    get_query() == v.get_query();
}
Beispiel #19
0
 void operator()(Uri &uri) const {
   uri.append(scheme);
   if (opaque_schemes::exists(scheme)) {
     uri.append(":");
   } else {
     uri.append("://");
   }
 }
Beispiel #20
0
Int32 Uri::Compare(const Uri& Uri1, const Uri& Uri2,
                   const UriComponents::Type PartToCompare,
                   const UriFormat::Type CompareFormat)
{
    String a=Uri1.GetComponents(PartToCompare,CompareFormat);
    String b=Uri2.GetComponents(PartToCompare,CompareFormat);
    return a.Compare(b);
}
Beispiel #21
0
 void Client::request(
     Method method, Uri uri,
     Header header,
     void *data, int len){
     
     TCPSocket *socket = new TCPSocket(
         uri.getDomain().c_str(), uri.getPort(),
         [=](int err, TCPSocket *socket){
             if( err != eNoError ){
                 EP_SAFE_DEFER( responseCallback, err, Header(),"" );
             }
             else{
                 string *buffer = new string();
                 
                 socket->onReceive(
                     [=](void *data, int len){
                         buffer->append( (char*)data );
                     });
                 socket->onUnbind(
                     [=](){
                         Header header;
                         string body;
                         int offset = header.load( *buffer );
                         
                         /*
                          todo : parse chunked content-length
                          */
                         header.getField(
                             "Transfer-Encoding");
                         
                         if( offset == - 1 ){
                             EP_SAFE_DEFER( responseCallback, eParseError, Header(),"" );
                         }
                         else{
                             body = buffer->substr( offset );
                             
                             EP_SAFE_DEFER( responseCallback, eNoError, header, body );
                         }
                         
                         delete buffer;
                     });
                 
                 string requestLine =
                     generateRequestLine( method, uri.getRequestUri(), "HTTP/1.1" );
                 string headerString =
                     header.dump();
                 
                 socket->write(
                     (void*)requestLine.c_str(), requestLine.size());
                 socket->write(
                     (void*)headerString.c_str(), headerString.size());
                 
                 if( len > 0 ){
                     socket->write( data, len );
                 }
             }
         });
 }
Beispiel #22
0
void CpiDeviceUpnp::GetServiceUri(Uri& aUri, const TChar* aType, const ServiceType& aServiceType)
{
    Brn root = XmlParserBasic::Find("root", iXml);
    Brn device = XmlParserBasic::Find("device", root);
    Brn udn = XmlParserBasic::Find("UDN", device);
    if (!CpiDeviceUpnp::UdnMatches(udn, Udn())) {
        Brn deviceList = XmlParserBasic::Find("deviceList", device);
        do {
            Brn remaining;
            device.Set(XmlParserBasic::Find("device", deviceList, remaining));
            udn.Set(XmlParserBasic::Find("UDN", device));
            deviceList.Set(remaining);
        } while (!CpiDeviceUpnp::UdnMatches(udn, Udn()));
    }
    Brn serviceList = XmlParserBasic::Find("serviceList", device);
    Brn service;
    Brn serviceType;
    Brn devServiceTypeNoVer;
    const Brx& targServiceType = aServiceType.FullName();
    // Must have backwards compatibility. Need to compare service type and version separately.
    Parser serviceParser = targServiceType;
    serviceParser.Next(':');    // urn
    serviceParser.Next(':');    // schema url
    serviceParser.Next(':');    // service
    serviceParser.Next(':');    // name
    Brn targServiceTypeNoVer(targServiceType.Ptr(), serviceParser.Index()); // full name minus ":x" (where x is version)
    do {
        Brn remaining;
        service.Set(XmlParserBasic::Find("service", serviceList, remaining));
        serviceType.Set(XmlParserBasic::Find("serviceType", service));
        serviceList.Set(remaining);
        // Parse service type and version separately.
        serviceParser.Set(serviceType);
        serviceParser.Next(':');    // urn
        serviceParser.Next(':');    // schema url
        serviceParser.Next(':');    // service
        serviceParser.Next(':');    // name
        devServiceTypeNoVer.Set(serviceType.Ptr(), serviceParser.Index()); // full name minus ":x" (where x is version)
        // MUST allow use of device with version >= target version
    } while (devServiceTypeNoVer != targServiceTypeNoVer);
    Brn path = XmlParserBasic::Find(aType, service);
    if (path.Bytes() == 0) {
        // no event url => service doesn't have any evented state variables
        THROW(XmlError);
    }

    // now create a uri using the scheme/host/port of the device xml location
    // plus the path we've just constructed
    Bws<40> base; // just need space for http://xxx.xxx.xxx.xxx:xxxxx
    aUri.Replace(iLocation);
    base.Append(aUri.Scheme());
    base.Append("://");
    base.Append(aUri.Host());
    base.Append(':');
    Ascii::AppendDec(base, aUri.Port());
    aUri.Replace(base, path);
}
Beispiel #23
0
//==============================================================================
std::string Uri::getRelativeUri(
    const Uri& _baseUri, const Uri& _relativeUri, bool _strict)
{
  Uri mergedUri;
  if(!mergedUri.fromRelativeUri(_baseUri, _relativeUri, _strict))
    return "";
  else
    return mergedUri.toString();
}
Beispiel #24
0
void EventUpnp::Unsubscribe(const Uri& aPublisher, const Brx& aSid)
{
    iSocket.Open(iCpStack.Env());
    Endpoint endpoint(aPublisher.Port(), aPublisher.Host());
    TUint timeout = iCpStack.Env().InitParams()->TcpConnectTimeoutMs();
    iSocket.Connect(endpoint, timeout);

    UnsubscribeWriteRequest(aPublisher, aSid);
    UnsubscribeReadResponse();
}
void RedirectionResolver::redirectionClean(const Uri & origin) {
  std::pair<std::string, std::string> query = std::make_pair(origin.getString(), "");
  while(true) {
    const std::pair<std::string, std::string> nextkey = redirCache.upper_bound(query);
      if(nextkey.first != origin.getString()) {
        break;
      }

    redirectionClean(nextkey.second, nextkey.first);
  }
}
Beispiel #26
0
void CpiDeviceUpnp::GetControlUri(const Invocation& aInvocation, Uri& aUri)
{
    AutoMutex a(iLock);
    if (iControlUrl.Bytes() != 0) {
        aUri.Replace(iControlUrl);
    }
    else {
        GetServiceUri(aUri, "controlURL", aInvocation.ServiceType());
        iControlUrl.Set(aUri.AbsoluteUri());
    }
}
Beispiel #27
0
void
HttpRequest::Open (const char *verb, const char *uri, DownloaderAccessPolicy policy)
{
    VERIFY_MAIN_THREAD;

    Uri *url = new Uri ();
    if (url->Parse (uri))
        Open (verb, url, policy);

    delete url;
}
Beispiel #28
0
 void operator()(Uri &uri) const {
   std::string encoded_key, encoded_query;
   if (boost::empty(uri.query())) {
     uri.append("?");
   } else {
     uri.append("&");
   }
   uri.append(key);
   uri.append("=");
   uri.append(query);
 }
Beispiel #29
0
static Uri parseUri(char const* str) {
    Uri uri;

    auto scheme = parseScheme(str);
    auto authority = parseAuthority(scheme.ch);
    auto path = parsePath(authority.ch);

    uri.schemeIs(scheme.value);
    uri.authorityIs(authority.value);
    uri.pathIs(path.value);
    return uri; 
}
Beispiel #30
0
List<Uri> BuiltinProtocolHandlersLocal::listDir(const Uri &uri)
{
    List<Uri> res;
    DIR *dir = ::opendir(uri.uri().data());
    struct dirent *dirEntry;
    while ((dirEntry = ::readdir(dir))) {
        const Uri uriEnt(uri.uri(), dirEntry->d_name);
        res.push_back(uriEnt);
    }
    ::closedir(dir);
    return res;
}