Example #1
0
static bool makeAllDirectories(IFileMgr* fileManager, const String& path)
{
    if (path == canonicalPath(AEEFS_HOME_DIR))
        return true;

    int lastDivPos = path.reverseFind('/');
    int endPos = path.length();
    if (lastDivPos == path.length() - 1) {
        endPos -= 1;
        lastDivPos = path.reverseFind('/', lastDivPos);
    }

    if (lastDivPos > 0) {
        if (!makeAllDirectories(fileManager, path.substring(0, lastDivPos)))
            return false;
    }

    String folder(path.substring(0, endPos));

    // IFILEMGR_MkDir return SUCCESS when the file is successfully created or if file already exists.
    // So we need to check fileinfo.attrib.
    IFILEMGR_MkDir(fileManager, folder.utf8().data());

    FileInfo fileInfo;
    if (IFILEMGR_GetInfo(fileManager, folder.utf8().data(), &fileInfo) != SUCCESS)
        return false;

    return fileInfo.attrib & _FA_DIR;
}
Example #2
0
PassRefPtr<Text> Text::splitText(unsigned offset, ExceptionState& exceptionState)
{
    // IndexSizeError: Raised if the specified offset is negative or greater than
    // the number of 16-bit units in data.
    if (offset > length()) {
        exceptionState.ThrowDOMException(IndexSizeError, "The offset " + String::number(offset) + " is larger than the Text node's length.");
        return nullptr;
    }

    String oldStr = data();
    RefPtr<Text> newText = cloneWithData(oldStr.substring(offset));
    setDataWithoutUpdate(oldStr.substring(0, offset));

    didModifyData(oldStr);

    if (parentNode())
        parentNode()->insertBefore(newText.get(), nextSibling(), exceptionState);
    if (exceptionState.had_exception())
        return nullptr;

    if (renderer())
        renderer()->setTextWithOffset(dataImpl(), 0, oldStr.length());

    if (parentNode())
        document().didSplitTextNode(*this);

    return newText.release();
}
Example #3
0
void HTMLAnchorElement::setHost(const String& value)
{
    if (value.isEmpty())
        return;
    KURL url = href();
    if (!url.canSetHostOrPort())
        return;

    size_t separator = value.find(':');
    if (!separator)
        return;

    if (separator == notFound)
        url.setHostAndPort(value);
    else {
        unsigned portEnd;
        unsigned port = parsePortFromStringPosition(value, separator + 1, portEnd);
        if (!port) {
            // http://dev.w3.org/html5/spec/infrastructure.html#url-decomposition-idl-attributes
            // specifically goes against RFC 3986 (p3.2) and
            // requires setting the port to "0" if it is set to empty string.
            url.setHostAndPort(value.substring(0, separator + 1) + "0");
        } else {
            if (isDefaultPortForProtocol(port, url.protocol()))
                url.setHostAndPort(value.substring(0, separator));
            else
                url.setHostAndPort(value.substring(0, portEnd));
        }
    }
    setHref(url.string());
}
Example #4
0
void VTTParser::collectMetadataHeader(const String& line)
{
    // WebVTT header parsing (WebVTT parser algorithm step 12)
    DEFINE_STATIC_LOCAL(const AtomicString, regionHeaderName, ("Region", AtomicString::ConstructFromLiteral));

    // The only currently supported header is the "Region" header.
    if (!RuntimeEnabledFeatures::webVTTRegionsEnabled())
        return;

    // Step 12.4 If line contains the character ":" (A U+003A COLON), then set metadata's
    // name to the substring of line before the first ":" character and
    // metadata's value to the substring after this character.
    size_t colonPosition = line.find(':');
    if (colonPosition == kNotFound)
        return;

    String headerName = line.substring(0, colonPosition);

    // Steps 12.5 If metadata's name equals "Region":
    if (headerName == regionHeaderName) {
        String headerValue = line.substring(colonPosition + 1);
        // Steps 12.5.1 - 12.5.11 Region creation: Let region be a new text track region [...]
        createNewRegion(headerValue);
    }
}
Example #5
0
/*******************************************************************************
 * Function Name  : tinkerDigitalWrite
 * Description    : Sets the specified pin HIGH or LOW
 * Input          : Pin and value
 * Output         : None.
 * Return         : 1 on success and a negative number on failure
 *******************************************************************************/
int tinkerDigitalWrite(String command)
{
    bool value = 0;
    //convert ascii to integer
    int pinNumber = command.charAt(1) - '0';
    //Sanity check to see if the pin numbers are within limits
    if (pinNumber< 0 || pinNumber >7) return -1;

    if(command.substring(3,7) == "HIGH") value = 1;
    else if(command.substring(3,6) == "LOW") value = 0;
    else return -2;

    if(command.startsWith("D"))
    {
        pinMode(pinNumber, OUTPUT);
        digitalWrite(pinNumber, value);
        return 1;
    }
    else if(command.startsWith("A"))
    {
        pinMode(pinNumber+10, OUTPUT);
        digitalWrite(pinNumber+10, value);
        return 1;
    }
    else return -3;
}
Example #6
0
PassRefPtr<SecurityOrigin> SecurityOrigin::createFromDatabaseIdentifier(const String& databaseIdentifier)
{ 
    // Make sure there's a first separator
    int separator1 = databaseIdentifier.find(SeparatorCharacter);
    if (separator1 == -1)
        return create(KURL());
        
    // Make sure there's a second separator
    int separator2 = databaseIdentifier.find(SeparatorCharacter, separator1 + 1);
    if (separator2 == -1)
        return create(KURL());
        
    // Make sure there's not a third separator
    if (databaseIdentifier.reverseFind(SeparatorCharacter) != separator2)
        return create(KURL());
        
    // Make sure the port section is a valid port number or doesn't exist
    bool portOkay;
    int port = databaseIdentifier.right(databaseIdentifier.length() - separator2 - 1).toInt(&portOkay);
    if (!portOkay && separator2 + 1 == static_cast<int>(databaseIdentifier.length()))
        return create(KURL());
    
    if (port < 0 || port > 65535)
        return create(KURL());
        
    // Split out the 3 sections of data
    String protocol = databaseIdentifier.substring(0, separator1);
    String host = databaseIdentifier.substring(separator1 + 1, separator2 - separator1 - 1);
    return create(KURL(KURL(), protocol + "://" + host + ":" + String::number(port)));
}
Example #7
0
char* HttpServer::ParseUrl(char *str)
{
  int8_t r=-1;
  int8_t i = 0;
  int index = 4;
  int index1 = 0;
  int plen = 0;
  char ch = str[index];
  char clientline[CMDBUF];
  while( ch != ' ' && index < CMDBUF)
  {
    clientline[index1++] = ch;
    ch = str[++index];
  }
  clientline[index1] = '\0';

  // convert clientline into a proper
  // string for further processing
  String urlString = String(clientline);

  // extract the operation
  String op = urlString.substring(0,urlString.indexOf(' '));

  // we're only interested in the first part...
  urlString = urlString.substring(urlString.indexOf('/'), urlString.indexOf(' ', urlString.indexOf('/')));

  // put what's left of the URL back in client line
  urlString.toCharArray(clientline, CMDBUF);

  return clientline;
}
String Utility::findValue(String input, String key) {
  Serial.println("Got: " + input);

  String ret = "Key not found: " + key;
  int eqIndex = input.indexOf('=');
  while (eqIndex > -1) {
    String k = input.substring(0, eqIndex);
    Serial.println("Found key: " + k);
    String v;
    int ampIndex = input.indexOf('&');
    if (ampIndex > -1) {
      v = input.substring(eqIndex + 1, ampIndex);
      input = input.substring(ampIndex + 1);
    } else {
      v = input.substring(eqIndex + 1);
      input = v;
    }
    Serial.println("Found value: " + v);
    if (k.equals(key)) {
      ret = v;
      break;
    } else {
      eqIndex = input.indexOf('=');
    }
  }

  return ret;
}
SMILTime SVGSMILElement::parseClockValue(const String& data)
{
    if (data.isNull())
        return SMILTime::unresolved();

    String parse = data.stripWhiteSpace();

    DEFINE_STATIC_LOCAL(const AtomicString, indefiniteValue, ("indefinite"));
    if (parse == indefiniteValue)
        return SMILTime::indefinite();

    double result = 0;
    bool ok;
    size_t doublePointOne = parse.find(':');
    size_t doublePointTwo = parse.find(':', doublePointOne + 1);
    if (doublePointOne == 2 && doublePointTwo == 5 && parse.length() >= 8) {
        result += parse.substring(0, 2).toUIntStrict(&ok) * 60 * 60;
        if (!ok)
            return SMILTime::unresolved();
        result += parse.substring(3, 2).toUIntStrict(&ok) * 60;
        if (!ok)
            return SMILTime::unresolved();
        result += parse.substring(6).toDouble(&ok);
    } else if (doublePointOne == 2 && doublePointTwo == kNotFound && parse.length() >= 5) {
        result += parse.substring(0, 2).toUIntStrict(&ok) * 60;
        if (!ok)
            return SMILTime::unresolved();
        result += parse.substring(3).toDouble(&ok);
    } else
        return parseOffsetValue(parse);

    if (!ok || !SMILTime(result).isFinite())
        return SMILTime::unresolved();
    return result;
}
void CNCArduinostepsClass::serialcalibratedx(String calibrcommand) // установка dxX и dxY с парсингом команды по последовательному порту
{
	//String calibrationtemp = calibrcommand.substring(0, calibrcommand.indexOf('&'));
	String dxtemp = calibrcommand;
	//Serial.println(calibrationtemp);
	//Serial.println(dxtemp);
	//double calibrationXtemp = calibrationtemp.substring(0, calibrationtemp.indexOf('$')).toFloat();
	//Serial.println(calibrationXtemp);
	//double calibrationYtemp = calibrationtemp.substring(calibrationtemp.indexOf('$') + 1, calibrationtemp.length()).toFloat();
	//Serial.println(calibrationYtemp);
	double dxXtemp = dxtemp.substring(0, dxtemp.indexOf('$')).toFloat();
	//Serial.println(dxXtemp);
	double dxYtemp = dxtemp.substring(dxtemp.indexOf('$') + 1, dxtemp.length()).toFloat();
	//Serial.println(dxYtemp);
	//double calibrationXtemp = amountstri.substring(0, amountstri.indexOf('$')).toFloat();
	///Serial.println(amountstri.substring(0, amountstri.indexOf('$')));
	//double calibrationYtemp = amountstri.substring(amountstri.indexOf('$')+1, amountstri.indexOf('&')).toFloat();
	//Serial.println(amountstri.substring(amountstri.indexOf('$')+1, amountstri.indexOf('&')));
	//double dxXtemp = amountstri.substring(amountstri.indexOf('&')+1, amountstri.indexOf('$')).toFloat();
	//Serial.println(amountstri.substring(amountstri.indexOf('&')+1, amountstri.indexOf('$')));
	//double dxYtemp = amountstri.substring(amountstri.indexOf('$')+1, amountstri.indexOf('#')).toFloat();
	//Serial.println(amountstri.substring(amountstri.indexOf('$')+1, amountstri.indexOf('#')));
	//Serial.println(calibrationXtemp);
	//Serial.println(calibrationYtemp);
	//Serial.println(dxXtemp);
	//Serial.println(dxYtemp);
	//setcalibration(calibrationXtemp, calibrationYtemp);
	setdxdy(dxXtemp, dxYtemp);

}
PassRefPtr<SecurityOrigin> SecurityOrigin::maybeCreateFromDatabaseIdentifier(const String& databaseIdentifier)
{ 
    // Make sure there's a first separator
    size_t separator1 = databaseIdentifier.find(separatorCharacter);
    if (separator1 == notFound)
        return nullptr;
        
    // Make sure there's a second separator
    size_t separator2 = databaseIdentifier.reverseFind(separatorCharacter);
    if (separator2 == notFound)
        return nullptr;

    // Ensure there were at least 2 separator characters. Some hostnames on intranets have
    // underscores in them, so we'll assume that any additional underscores are part of the host.
    if (separator1 == separator2)
        return nullptr;

    // Make sure the port section is a valid port number or doesn't exist
    bool portOkay;
    int port = databaseIdentifier.right(databaseIdentifier.length() - separator2 - 1).toInt(&portOkay);
    bool portAbsent = (separator2 == databaseIdentifier.length() - 1);
    if (!(portOkay || portAbsent))
        return nullptr;

    if (port < 0 || port > MaxAllowedPort)
        return nullptr;

    // Split out the 3 sections of data
    String protocol = databaseIdentifier.substring(0, separator1);
    String host = databaseIdentifier.substring(separator1 + 1, separator2 - separator1 - 1);
    
    host = decodeURLEscapeSequences(host);
    return create(URL(URL(), protocol + "://" + host + ":" + String::number(port) + "/"));
}
bool KeyValueStore::migrate() {
  if (!SPIFFS.exists(FILENAME_OLD)) {
    return true;
  }
  StaticJsonBuffer<300> jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();

  File f = SPIFFS.open(FILENAME_OLD, "r");
  if (!f) {
    return false;
  }
  while(f.available()) {
    String line = f.readStringUntil('\n');
    int separator = line.indexOf("=");
    if (separator > -1) {
      String key = line.substring(0, separator);
      String value = line.substring(separator + 1);
      value.trim();
      root[key] = value;
    }
  }
  f.close();
  clear(FILENAME_JSON);
  File fJson = SPIFFS.open(FILENAME_JSON, "w");
  root.printTo(fJson);
  fJson.close();
  Serial.println("Migrated KeyValueStore to JSON:");
  root.prettyPrintTo(Serial);
  Serial.println();
  clear(FILENAME_OLD);
  return true;
}
Example #13
0
String TicketflySDBeacon::TicketInfoParser (String TicketString, int typeReturn){ 
  String TicketNumberRetrieve = "", TicketNameRetrieve = "", TicketTypeRetrieve = "";
  int lengthString, commaIndex1, commaIndex2;
  TicketString.replace(" ", "");
  lengthString = TicketString.length();
  commaIndex1 = TicketString.indexOf(',');
  commaIndex2 = TicketString.indexOf(',', commaIndex1+1);
    switch (typeReturn){
      case 1:
        TicketNumberRetrieve = TicketString.substring (0, commaIndex1);
        return TicketNumberRetrieve;
        break;
      case 2:
        TicketNameRetrieve = TicketString.substring (commaIndex1+1, commaIndex2);
        return TicketNameRetrieve;
        break;
      case 3:
        TicketTypeRetrieve = TicketString.substring (commaIndex2+1, lengthString);
        return TicketTypeRetrieve;
        break;
      default:
        return "empty";
        Serial.println (F("this is not an acceptable input"));
        break;
    }
}
Example #14
0
String Engine::get_var(String request, String response_prefix)
{
   Conroller_port.flush();
   unsigned long time = micros() + 100;
   while( micros() < time )
   {
      if( Conroller_port.available() )
      {
         Conroller_port.read();
         time = micros() + 100;
      }
   }
   Conroller_port.println(request);
   time = micros() + 2000;
   String res = "";
   while( micros() < time )
   {
      if( !Conroller_port.available() ) continue;
      char c = (char)Conroller_port.read();
      if( c != '\r' )
      {
          res += c;
          continue;
      }
      if( res.substring(0, 2).equals(response_prefix) ) return res.substring(2);
      res = "";
   }
   return "";
}
//Function that control the specific brightness of the led conected to specific pwmpin.
//the structure of the command is pwmpin:brightness
int controlPWM(String command) {
     int index=command.indexOf(":");
     String pwmpin=command.substring(0,index);
     String val=command.substring(index+1);
     int pin=pwmpin.toInt();
     int value=val.toInt();
    if (value<256&&value>=0){
        analogWrite(pin,value);
        if (pin==10){
            EEPROMData.outputData.pwmoutput[2].pin=pin;
            EEPROMData.outputData.pwmoutput[2].value=value;
         }
        else if (pin==11){
            EEPROMData.outputData.pwmoutput[3].pin=pin;
            EEPROMData.outputData.pwmoutput[3].value=value;
        }
        else if (pin>13&&pin<18){
            EEPROMData.outputData.pwmoutput[pin-10].pin=pin;
            EEPROMData.outputData.pwmoutput[pin-10].value=value;
        }
        else if (pin<2){
            EEPROMData.outputData.pwmoutput[pin].pin=pin;
            EEPROMData.outputData.pwmoutput[pin].value=value;
        }
        writeEEPROM();
        return value;
    }
    else{
        return -1;// return -1 if the pin sended on the command is not the PWM output ones
    }
}
Example #16
0
float GPSInterface::convert(String str, boolean dir) {
  double mm, dd;
  int point = str.indexOf('.');
  dd = str.substring(0, (point - 2)).toFloat();
  mm = str.substring(point - 2).toFloat() / 60.00;
  return (dir ? -1 : 1) * (dd + mm);
}
Example #17
0
KURL DOMFileSystemBase::createFileSystemURL(const String& fullPath) const {
  ASSERT(DOMFilePath::isAbsolute(fullPath));

  if (type() == FileSystemTypeExternal) {
    // For external filesystem originString could be different from what we have
    // in m_filesystemRootURL.
    StringBuilder result;
    result.append("filesystem:");
    result.append(getSecurityOrigin()->toString());
    result.append('/');
    result.append(externalPathPrefix);
    result.append(m_filesystemRootURL.path());
    // Remove the extra leading slash.
    result.append(encodeWithURLEscapeSequences(fullPath.substring(1)));
    return KURL(ParsedURLString, result.toString());
  }

  // For regular types we can just append the entry's fullPath to the
  // m_filesystemRootURL that should look like
  // 'filesystem:<origin>/<typePrefix>'.
  ASSERT(!m_filesystemRootURL.isEmpty());
  KURL url = m_filesystemRootURL;
  // Remove the extra leading slash.
  url.setPath(url.path() + encodeWithURLEscapeSequences(fullPath.substring(1)));
  return url;
}
Example #18
0
	bool yl_messenger::recv_ln_start_with(const String start, String &data)
	{
		String start_temp(start);
		start_temp.toLowerCase();
		for (;;)
		{
			String temp;
			if (!recv_ln(temp))
			{
#ifdef YL_SERIAL_DEBUG
				Serial.println("read error : 245");
#endif
				return false;
			}
			temp.toLowerCase();
			if (temp == start_temp)
			{
				return recv_ln(data);
			}
			if (temp.substring(0, start_temp.length()) == start_temp)
			{
				data = temp.substring(start_temp.length());
				return true;
			}
		}
		return false;
	}
Example #19
0
static RegularExpression* createRegExpForLabels(const Vector<String>& labels)
{
    // REVIEW- version of this call in FrameMac.mm caches based on the NSArray ptrs being
    // the same across calls.  We can't do that.

    DEFINE_STATIC_LOCAL(RegularExpression, wordRegExp, ("\\w", TextCaseSensitive));
    String pattern("(");
    unsigned int numLabels = labels.size();
    unsigned int i;
    for (i = 0; i < numLabels; i++) {
        String label = labels[i];

        bool startsWithWordChar = false;
        bool endsWithWordChar = false;
        if (label.length()) {
            startsWithWordChar = wordRegExp.match(label.substring(0, 1)) >= 0;
            endsWithWordChar = wordRegExp.match(label.substring(label.length() - 1, 1)) >= 0;
        }

        if (i)
            pattern.append("|");
        // Search for word boundaries only if label starts/ends with "word characters".
        // If we always searched for word boundaries, this wouldn't work for languages
        // such as Japanese.
        if (startsWithWordChar)
            pattern.append("\\b");
        pattern.append(label);
        if (endsWithWordChar)
            pattern.append("\\b");
    }
    pattern.append(")");
    return new RegularExpression(pattern, TextCaseInsensitive);
}
Example #20
0
RefPtr<Text> Text::splitText(unsigned offset, ExceptionCode& ec)
{
    ec = 0;

    // INDEX_SIZE_ERR: Raised if the specified offset is negative or greater than
    // the number of 16-bit units in data.
    if (offset > length()) {
        ec = INDEX_SIZE_ERR;
        return 0;
    }

    EventQueueScope scope;
    String oldStr = data();
    Ref<Text> newText = virtualCreate(oldStr.substring(offset));
    setDataWithoutUpdate(oldStr.substring(0, offset));

    dispatchModifiedEvent(oldStr);

    if (parentNode())
        parentNode()->insertBefore(newText.ptr(), nextSibling(), ec);
    if (ec)
        return 0;

    if (parentNode())
        document().textNodeSplit(this);

    if (renderer())
        renderer()->setTextWithOffset(data(), 0, oldStr.length());

    return WTF::move(newText);
}
Example #21
0
static CString pathSuitableForTestResult(const char* uriString)
{
    if (!uriString)
        return CString();

    KURL uri = KURL(ParsedURLString, uriString);

    if (!uri.isLocalFile())
        return uri.string().utf8();

    String pathString = uri.path();
    size_t indexBaseName = pathString.reverseFind('/');
    String baseName;
    if (indexBaseName == notFound)
        baseName = pathString;
    else
        baseName = pathString.substring(indexBaseName + 1);

    String dirName;
    if (indexBaseName != notFound) {
        size_t indexDirName = pathString.reverseFind('/', indexBaseName - 1);
        if (indexDirName != notFound)
            dirName = pathString.substring(indexDirName + 1, indexBaseName - indexDirName - 1);
    }

    String ret = dirName + "/" + baseName;
    return ret.utf8();
}
Example #22
0
static KeyValueMap retrieveKeyValuePairs(WebCore::SharedBufferChunkReader* buffer)
{
    KeyValueMap keyValuePairs;
    String line;
    String key;
    StringBuilder value;
    while (!(line = buffer->nextChunkAsUTF8StringWithLatin1Fallback()).isNull()) {
        if (line.isEmpty())
            break; // Empty line means end of key/value section.
        if (line[0] == '\t') {
            ASSERT(!key.isEmpty());
            value.append(line.substring(1));
            continue;
        }
        // New key/value, store the previous one if any.
        if (!key.isEmpty()) {
            if (keyValuePairs.find(key) != keyValuePairs.end())
                LOG_ERROR("Key duplicate found in MIME header. Key is '%s', previous value replaced.", key.ascii().data());
            keyValuePairs.add(key, value.toString().stripWhiteSpace());
            key = String();
            value.clear();
        }
        size_t semiColonIndex = line.find(':');
        if (semiColonIndex == notFound) {
            // This is not a key value pair, ignore.
            continue;
        }
        key = line.substring(0, semiColonIndex).lower().stripWhiteSpace();
        value.append(line.substring(semiColonIndex + 1));
    }
    // Store the last property if there is one.
    if (!key.isEmpty())
        keyValuePairs.set(key, value.toString().stripWhiteSpace());
    return keyValuePairs;
}
Example #23
0
void Configuration::begin() {
	size = computeLines();
	Serial.printf("size: %d\n", size);
	if (size > 0) {
		properties = new pair[size];
		File f = SPIFFS.open(fileName, "r");
		if (f) {
			for (int i = 0; i < size; i++) {
				String line = f.readStringUntil('\n');
				int ind = line.indexOf('=');

				if (ind != -1) {
					properties[i].key = line.substring(0, ind);
					properties[i].key.trim();
					properties[i].value = line.substring(ind + 1);
					properties[i].value.trim();
					Serial.printf("read from file: |%s=%s|\n",
							properties[i].key.c_str(),
							properties[i].value.c_str());
				}
			}
			f.close();
		}
	}
}
static YouTubePluginReplacement::KeyValueMap queryKeysAndValues(const String& queryString)
{
    YouTubePluginReplacement::KeyValueMap queryDictionary;
    
    size_t queryLength = queryString.length();
    if (!queryLength)
        return queryDictionary;
    
    size_t equalSearchLocation = 0;
    size_t equalSearchLength = queryLength;
    
    while (equalSearchLocation < queryLength - 1 && equalSearchLength) {
        
        // Search for "=".
        size_t equalLocation = queryString.find('=', equalSearchLocation);
        if (equalLocation == notFound)
            break;
        
        size_t indexAfterEqual = equalLocation + 1;
        if (indexAfterEqual > queryLength - 1)
            break;
        
        // Get the key before the "=".
        size_t keyLocation = equalSearchLocation;
        size_t keyLength = equalLocation - equalSearchLocation;
        
        // Seach for the ampersand.
        size_t ampersandLocation = queryString.find('&', indexAfterEqual);
        
        // Get the value after the "=", before the ampersand.
        size_t valueLocation = indexAfterEqual;
        size_t valueLength;
        if (ampersandLocation != notFound)
            valueLength = ampersandLocation - indexAfterEqual;
        else
            valueLength = queryLength - indexAfterEqual;
        
        // Save the key and the value.
        if (keyLength && valueLength) {
            const String& key = queryString.substring(keyLocation, keyLength).lower();
            String value = queryString.substring(valueLocation, valueLength);
            value.replace('+', ' ');

            if (!key.isEmpty() && !value.isEmpty())
                queryDictionary.add(key, value);
        }
        
        if (ampersandLocation == notFound)
            break;
        
        // Continue searching after the ampersand.
        size_t indexAfterAmpersand = ampersandLocation + 1;
        equalSearchLocation = indexAfterAmpersand;
        equalSearchLength = queryLength - indexAfterAmpersand;
    }
    
    return queryDictionary;
}
Example #25
0
uint32_t strToColor(String strColor) {
	uint8_t r, g, b;

    r = atoi(strColor.substring(0,3).c_str());
	g = atoi(strColor.substring(3,6).c_str());
	b = atoi(strColor.substring(6,9).c_str());
    
	return strip.Color(r, g, b);
}
void ipArrayFromString(byte ipArray[], String ipString) {
  int dot1 = ipString.indexOf('.');
  ipArray[0] = ipString.substring(0, dot1).toInt();
  int dot2 = ipString.indexOf('.', dot1 + 1);
  ipArray[1] = ipString.substring(dot1 + 1, dot2).toInt();
  dot1 = ipString.indexOf('.', dot2 + 1);
  ipArray[2] = ipString.substring(dot2 + 1, dot1).toInt();
  ipArray[3] = ipString.substring(dot1 + 1).toInt();
}
void MediaFragmentURIParser::parseFragments()
{
    if (!m_url.hasFragmentIdentifier())
        return;
    String fragmentString = m_url.fragmentIdentifier();
    if (fragmentString.isEmpty())
        return;

    unsigned offset = 0;
    unsigned end = fragmentString.length();
    while (offset < end) {
        // http://www.w3.org/2008/WebVideo/Fragments/WD-media-fragments-spec/#processing-name-value-components
        // 1. Parse the octet string according to the namevalues syntax, yielding a list of 
        //    name-value pairs, where name and value are both octet string. In accordance 
        //    with RFC 3986, the name and value components must be parsed and separated before
        //    percent-encoded octets are decoded.
        size_t parameterStart = offset;
        size_t parameterEnd = fragmentString.find('&', offset);
        if (parameterEnd == notFound)
            parameterEnd = end;

        size_t equalOffset = fragmentString.find('=', offset);
        if (equalOffset == notFound || equalOffset > parameterEnd) {
            offset = parameterEnd + 1;
            continue;
        }

        // 2. For each name-value pair:
        //  a. Decode percent-encoded octets in name and value as defined by RFC 3986. If either
        //     name or value are not valid percent-encoded strings, then remove the name-value pair
        //     from the list.
        String name = decodeURLEscapeSequences(fragmentString.substring(parameterStart, equalOffset - parameterStart));
        String value;
        if (equalOffset != parameterEnd)
            value = decodeURLEscapeSequences(fragmentString.substring(equalOffset + 1, parameterEnd - equalOffset - 1));
        
        //  b. Convert name and value to Unicode strings by interpreting them as UTF-8. If either
        //     name or value are not valid UTF-8 strings, then remove the name-value pair from the list.
        bool validUTF8 = false;
        if (!name.isEmpty() && !value.isEmpty()) {
            name = name.utf8(StrictConversion).data();
            validUTF8 = !name.isEmpty();

            if (validUTF8) {
                value = value.utf8(StrictConversion).data();
                validUTF8 = !value.isEmpty();
            }
        }
        
        if (validUTF8)
            m_fragments.append(std::make_pair(name, value));

        offset = parameterEnd + 1;
    }
}
static void parseCacheHeader(const String& header, Vector<std::pair<String, String>>& result)
{
    const String safeHeader = header.removeCharacters(isControlCharacter);
    unsigned max = safeHeader.length();
    for (unsigned pos = 0; pos < max; /* pos incremented in loop */) {
        size_t nextCommaPosition = safeHeader.find(',', pos);
        size_t nextEqualSignPosition = safeHeader.find('=', pos);
        if (nextEqualSignPosition != kNotFound && (nextEqualSignPosition < nextCommaPosition || nextCommaPosition == kNotFound)) {
            // Get directive name, parse right hand side of equal sign, then add to map
            String directive = trimToNextSeparator(safeHeader.substring(pos, nextEqualSignPosition - pos).stripWhiteSpace());
            pos += nextEqualSignPosition - pos + 1;

            String value = safeHeader.substring(pos, max - pos).stripWhiteSpace();
            if (value[0] == '"') {
                // The value is a quoted string
                size_t nextDoubleQuotePosition = value.find('"', 1);
                if (nextDoubleQuotePosition != kNotFound) {
                    // Store the value as a quoted string without quotes
                    result.append(std::pair<String, String>(directive, value.substring(1, nextDoubleQuotePosition - 1).stripWhiteSpace()));
                    pos += (safeHeader.find('"', pos) - pos) + nextDoubleQuotePosition + 1;
                    // Move past next comma, if there is one
                    size_t nextCommaPosition2 = safeHeader.find(',', pos);
                    if (nextCommaPosition2 != kNotFound)
                        pos += nextCommaPosition2 - pos + 1;
                    else
                        return; // Parse error if there is anything left with no comma
                } else {
                    // Parse error; just use the rest as the value
                    result.append(std::pair<String, String>(directive, trimToNextSeparator(value.substring(1, value.length() - 1).stripWhiteSpace())));
                    return;
                }
            } else {
                // The value is a token until the next comma
                size_t nextCommaPosition2 = value.find(',');
                if (nextCommaPosition2 != kNotFound) {
                    // The value is delimited by the next comma
                    result.append(std::pair<String, String>(directive, trimToNextSeparator(value.substring(0, nextCommaPosition2).stripWhiteSpace())));
                    pos += (safeHeader.find(',', pos) - pos) + 1;
                } else {
                    // The rest is the value; no change to value needed
                    result.append(std::pair<String, String>(directive, trimToNextSeparator(value)));
                    return;
                }
            }
        } else if (nextCommaPosition != kNotFound && (nextCommaPosition < nextEqualSignPosition || nextEqualSignPosition == kNotFound)) {
            // Add directive to map with empty string as value
            result.append(std::pair<String, String>(trimToNextSeparator(safeHeader.substring(pos, nextCommaPosition - pos).stripWhiteSpace()), ""));
            pos += nextCommaPosition - pos + 1;
        } else {
            // Add last directive to map with empty string as value
            result.append(std::pair<String, String>(trimToNextSeparator(safeHeader.substring(pos, max - pos).stripWhiteSpace()), ""));
            return;
        }
    }
}
Example #29
0
String createGUID (const String& seed)
{
    const String hex (MD5 ((seed + "_guidsalt").toUTF8()).toHexString().toUpperCase());

    return "{" + hex.substring (0, 8)
         + "-" + hex.substring (8, 12)
         + "-" + hex.substring (12, 16)
         + "-" + hex.substring (16, 20)
         + "-" + hex.substring (20, 32)
         + "}";
}
Example #30
0
void handleDataURL(ResourceHandle* handle)
{
    ASSERT(handle->firstRequest().url().protocolIs("data"));
    String url = handle->firstRequest().url().string();

    int index = url.find(',');
    if (index == -1) {
        handle->client()->cannotShowURL(handle);
        return;
    }

    String mediaType = url.substring(5, index - 5);
    String data = url.substring(index + 1);

    bool base64 = mediaType.endsWith(";base64", false);
    if (base64)
        mediaType = mediaType.left(mediaType.length() - 7);

    if (mediaType.isEmpty())
        mediaType = "text/plain";

    String mimeType = extractMIMETypeFromMediaType(mediaType);
    String charset = extractCharsetFromMediaType(mediaType);

    if (charset.isEmpty())
        charset = "US-ASCII";

    ResourceResponse response;
    response.setMimeType(mimeType);
    response.setTextEncodingName(charset);
    response.setURL(handle->firstRequest().url());

    if (base64) {
        data = decodeURLEscapeSequences(data);
        handle->client()->didReceiveResponse(handle, response);

        Vector<char> out;
        if (base64Decode(data, out, IgnoreWhitespace) && out.size() > 0) {
            response.setExpectedContentLength(out.size());
            handle->client()->didReceiveData(handle, out.data(), out.size(), 0);
        }
    } else {
        TextEncoding encoding(charset);
        data = decodeURLEscapeSequences(data, encoding);
        handle->client()->didReceiveResponse(handle, response);

        CString encodedData = encoding.encode(data.characters(), data.length(), URLEncodedEntitiesForUnencodables);
        response.setExpectedContentLength(encodedData.length());
        if (encodedData.length())
            handle->client()->didReceiveData(handle, encodedData.data(), encodedData.length(), 0);
    }

    handle->client()->didFinishLoading(handle, 0);
}