void MtpObjectInfo::read(MtpDataPacket& packet) {
    MtpStringBuffer string;
    time_t time;

    mStorageID = packet.getUInt32();
    mFormat = packet.getUInt16();
    mProtectionStatus = packet.getUInt16();
    mCompressedSize = packet.getUInt32();
    mThumbFormat = packet.getUInt16();
    mThumbCompressedSize = packet.getUInt32();
    mThumbPixWidth = packet.getUInt32();
    mThumbPixHeight = packet.getUInt32();
    mImagePixWidth = packet.getUInt32();
    mImagePixHeight = packet.getUInt32();
    mImagePixDepth = packet.getUInt32();
    mParent = packet.getUInt32();
    mAssociationType = packet.getUInt16();
    mAssociationDesc = packet.getUInt32();
    mSequenceNumber = packet.getUInt32();

    packet.getString(string);
    mName = strdup((const char *)string);

    packet.getString(string);
    if (parseDateTime((const char*)string, time))
        mDateCreated = time;

    packet.getString(string);
    if (parseDateTime((const char*)string, time))
        mDateModified = time;

    packet.getString(string);
    mKeywords = strdup((const char *)string);
}
TaskLog* AllneticImportHandler::parseTaskLog(QXmlAttributes attrs) {
    TaskLog* log = new TaskLog();
    log->id = uuid();
    log->start = parseDateTime(attrs.value(QString("start")));
    log->end = parseDateTime(attrs.value(QString("finish")));

    return log;
}
Task* AllneticImportHandler::parseTask(QXmlAttributes attrs) {
    Task* tsk = new Task(_currentProject);
    string* name = new string(attrs.value(QString("name")).toStdString());
    tsk->setShortDescription(name);

    tsk->setStartDate(parseDateTime(attrs.value("start")));
    tsk->setEndDate(parseDateTime(attrs.value("finish")));
    tsk->setDuration(Duration(1, 0, 0));
    tsk->setId(new string(attrs.value(QString("number")).toStdString()));
    tsk->setTemplateName(_defaultTemplate->name());
    tsk->setStatus(_defaultStatus);

    return tsk;
}
Beispiel #4
0
void parseDataValue(proto_tree *tree, tvbuff_t *tvb, gint *pOffset, const char *szFieldName)
{
    proto_item *ti = proto_tree_add_text(tree, tvb, *pOffset, -1, "%s: DataValue", szFieldName);
    proto_tree *subtree = proto_item_add_subtree(ti, ett_opcua_datavalue);
    proto_tree *mask_tree;
    gint    iOffset = *pOffset;
    guint8  EncodingMask;
    proto_item *ti_inner;

    EncodingMask = tvb_get_guint8(tvb, iOffset);
    ti_inner = proto_tree_add_text(subtree, tvb, iOffset, 1, "EncodingMask");
    mask_tree = proto_item_add_subtree(ti_inner, ett_opcua_datavalue);
    proto_tree_add_item(mask_tree, hf_opcua_datavalue_mask_valueflag,           tvb, iOffset, 1, ENC_LITTLE_ENDIAN);
    proto_tree_add_item(mask_tree, hf_opcua_datavalue_mask_statuscodeflag,      tvb, iOffset, 1, ENC_LITTLE_ENDIAN);
    proto_tree_add_item(mask_tree, hf_opcua_datavalue_mask_sourcetimestampflag, tvb, iOffset, 1, ENC_LITTLE_ENDIAN);
    proto_tree_add_item(mask_tree, hf_opcua_datavalue_mask_servertimestampflag, tvb, iOffset, 1, ENC_LITTLE_ENDIAN);
    proto_tree_add_item(mask_tree, hf_opcua_datavalue_mask_sourcepicoseconds,   tvb, iOffset, 1, ENC_LITTLE_ENDIAN);
    proto_tree_add_item(mask_tree, hf_opcua_datavalue_mask_serverpicoseconds,   tvb, iOffset, 1, ENC_LITTLE_ENDIAN);
    iOffset++;

    if (EncodingMask & DATAVALUE_ENCODINGBYTE_VALUE)
    {
        parseVariant(subtree, tvb, &iOffset, "Value");
    }
    if (EncodingMask & DATAVALUE_ENCODINGBYTE_STATUSCODE)
    {
        parseStatusCode(subtree, tvb, &iOffset, hf_opcua_StatusCode);
    }
    if (EncodingMask & DATAVALUE_ENCODINGBYTE_SOURCETIMESTAMP)
    {
        parseDateTime(subtree, tvb, &iOffset, hf_opcua_SourceTimestamp);
    }
    if (EncodingMask & DATAVALUE_ENCODINGBYTE_SOURCEPICOSECONDS)
    {
        parseUInt16(subtree, tvb, &iOffset, hf_opcua_SourcePicoseconds);
    }
    if (EncodingMask & DATAVALUE_ENCODINGBYTE_SERVERTIMESTAMP)
    {
        parseDateTime(subtree, tvb, &iOffset, hf_opcua_ServerTimestamp);
    }
    if (EncodingMask & DATAVALUE_ENCODINGBYTE_SERVERPICOSECONDS)
    {
        parseUInt16(subtree, tvb, &iOffset, hf_opcua_ServerPicoseconds);
    }

    proto_item_set_end(ti, tvb, iOffset);
    *pOffset = iOffset;
}
void ZipLocalFileHeader::parse(std::istream& inp, bool assumeHeaderRead)
{
    if (!assumeHeaderRead)
    {
        inp.read(_rawHeader, ZipCommon::HEADER_SIZE);
    }
    else
    {
        std::memcpy(_rawHeader, HEADER, ZipCommon::HEADER_SIZE);
    }
    poco_assert (std::memcmp(_rawHeader, HEADER, ZipCommon::HEADER_SIZE) == 0);
    // read the rest of the header
    inp.read(_rawHeader + ZipCommon::HEADER_SIZE, FULLHEADER_SIZE - ZipCommon::HEADER_SIZE);
    poco_assert (_rawHeader[VERSION_POS + 1]>= ZipCommon::HS_FAT && _rawHeader[VERSION_POS + 1] < ZipCommon::HS_UNUSED);
    poco_assert (getMajorVersionNumber() <= 4); // Allow for Zip64 version 4.5
    poco_assert (ZipUtil::get16BitValue(_rawHeader, COMPR_METHOD_POS) < ZipCommon::CM_UNUSED);
    parseDateTime();
    Poco::UInt16 len = getFileNameLength();
    Poco::Buffer<char> buf(len);
    inp.read(buf.begin(), len);
    _fileName = std::string(buf.begin(), len);

    if (!searchCRCAndSizesAfterData())
    {
        _crc32 = getCRCFromHeader();
        _compressedSize = getCompressedSizeFromHeader();
        _uncompressedSize = getUncompressedSizeFromHeader();
    }

    if (hasExtraField())
    {
        len = getExtraFieldLength();
        Poco::Buffer<char> xtra(len);
        inp.read(xtra.begin(), len);
        _extraField = std::string(xtra.begin(), len);
        char* ptr = xtra.begin();
        while (ptr <= xtra.begin() + len - 4) 
        {
            Poco::UInt16 id = ZipUtil::get16BitValue(ptr, 0); ptr +=2;
            Poco::UInt16 size = ZipUtil::get16BitValue(ptr, 0); ptr += 2;
            if (id == ZipCommon::ZIP64_EXTRA_ID) 
            {
                poco_assert(size >= 8);
                if (getUncompressedSizeFromHeader() == ZipCommon::ZIP64_MAGIC) 
                {
                    setUncompressedSize(ZipUtil::get64BitValue(ptr, 0)); size -= 8; ptr += 8;
                }
                if (size >= 8 && getCompressedSizeFromHeader() == ZipCommon::ZIP64_MAGIC) 
                {
                    setCompressedSize(ZipUtil::get64BitValue(ptr, 0)); size -= 8; ptr += 8;
                }
            } 
            else 
            {
                ptr += size;
            }
        }
    }

}
Beispiel #6
0
void ZipLocalFileHeader::parse(std::istream& inp, bool assumeHeaderRead)
{
    if (!assumeHeaderRead)
    {
        inp.read(_rawHeader, ZipCommon::HEADER_SIZE);
    }
    else
    {
        std::memcpy(_rawHeader, HEADER, ZipCommon::HEADER_SIZE);
    }
    poco_assert (std::memcmp(_rawHeader, HEADER, ZipCommon::HEADER_SIZE) == 0);
    // read the rest of the header
    inp.read(_rawHeader + ZipCommon::HEADER_SIZE, FULLHEADER_SIZE - ZipCommon::HEADER_SIZE);
    poco_assert (_rawHeader[VERSION_POS + 1]>= ZipCommon::HS_FAT && _rawHeader[VERSION_POS + 1] < ZipCommon::HS_UNUSED);
    poco_assert (getMajorVersionNumber() <= 2);
    poco_assert (ZipUtil::get16BitValue(_rawHeader, COMPR_METHOD_POS) < ZipCommon::CM_UNUSED);
    parseDateTime();
    Poco::UInt16 len = getFileNameLength();
    Poco::Buffer<char> buf(len);
    inp.read(buf.begin(), len);
    _fileName = std::string(buf.begin(), len);
    if (hasExtraField())
    {
        len = getExtraFieldLength();
        Poco::Buffer<char> xtra(len);
        inp.read(xtra.begin(), len);
        _extraField = std::string(xtra.begin(), len);
    }
    if (!searchCRCAndSizesAfterData())
    {
        _crc32 = getCRCFromHeader();
        _compressedSize = getCompressedSizeFromHeader();
        _uncompressedSize = getUncompressedSizeFromHeader();
    }
}
Beispiel #7
0
bool cRtEpgData::setEventData(const std::string& data, int timeOffset, bool isAscii)
{
    std::string latin = data;
    if (!isAscii)
    {
        latin = convertUTF8DVB(data, 1);
    }
    string::size_type index = data.find('~');
    int previous = 0;
    while (index != string::npos)
    {
        strings.push_back( data.substr(previous, index-previous));
        previous = index + 1;
        index = data.find('~', previous);
    }
    strings.push_back( data.substr(previous));  //don't forget last one - not terminated with a '~'

    if (strings.size() == 23)
    {
        name        = strings[0];
        subtitle    = strings[1];
        episode     = strings[2];
        year        = atoi(strings[3].c_str());
        director    = strings[4];
        cast        = strings[5];
        premiere    = strings[6] == "true";
        film        = strings[7] == "true";
        repeat      = strings[8] == "true";
        subtitled   = strings[9] == "true";
        widescreen  = strings[10] == "true";
        new_series  = strings[11] == "true";
        deaf_signed = strings[12] == "true";
        black_white = strings[13] == "true";
        starRating  = atoi(strings[14].c_str());
        certificate = atoi(strings[15].c_str());
        genre       = strings[16];
        description = strings[17];
        choice      = strings[18] == "true";
        startdate   = strings[19];
        starttime   = strings[20];
        stoptime    = strings[21];
        duration    = atoi(strings[22].c_str());
        offset      = timeOffset;

        /* start time is given in UK local time (GMT or GMT+1)
        I need gmt time, so I convert the time as if it was a local time, and then
        account for the timezone difference.
        Because our daylight saving times/summer times move in sync, the difference
        remains constant. ==> this means we can use our local timezone to determine
        the offset.
        can this go wrong? esp during changeovers?
        */
        startTime = parseDateTime(startdate, starttime) + offset;
        stopTime = startTime + duration*60;
        return true;
    }

    return false;
}
QString WeatherPlugin::replace(const QString &text)
{
    QString res = text;
    QString sun_set, sun_raise, updated;
#if COMPAT_QT_VERSION >= 0x030000
    QTime tmp_time;
    QDateTime dt;
    int h,m;

    parseTime(getSun_set(),h,m);
    tmp_time.setHMS(h,m,0,0);
    sun_set = tmp_time.toString(Qt::LocalDate);
    sun_set = sun_set.left(sun_set.length() - 3);

    parseTime(getSun_raise(),h,m);
    tmp_time.setHMS(h,m,0,0);
    sun_raise = tmp_time.toString(Qt::LocalDate);
    sun_raise = sun_raise.left(sun_raise.length() - 3);

    parseDateTime(getUpdated(),dt);
    updated = dt.toString(Qt::LocalDate);
    updated = updated.left(updated.length() - 3);
#else
    sun_set = getSun_set();
    sun_raise = getSun_raise();
    updated = getUpdated();
#endif
    /* double Expressions *before* single or better RegExp ! */
    res = res.replace(QRegExp("\\%mp"), i18n("moonphase", getMoonPhase()));
    res = res.replace(QRegExp("\\%mi"), number(getMoonIcon()));
    res = res.replace(QRegExp("\\%pp"), number(getPrecipitation()));
	res = res.replace(QRegExp("\\%ut"), i18n("weather", getUV_Description()));
	res = res.replace(QRegExp("\\%ui"), number(getUV_Intensity()));
    res = res.replace(QRegExp("\\%t"), QString::number((int)getTemperature()) + QChar((unsigned short)176) + getUT());
    res = res.replace(QRegExp("\\%f"), QString::number((int)getFeelsLike()) + QChar((unsigned short)176) + getUT());
    res = res.replace(QRegExp("\\%d"), QString::number((int)getDewPoint()) + QChar((unsigned short)176) + getUT());
    res = res.replace(QRegExp("\\%h"), number(getHumidity()) + "%");
    res = res.replace(QRegExp("\\%w"), number(getWind_speed()) + " " + i18n(getUS()));
    res = res.replace(QRegExp("\\%x"), QString::number(getWind_speed() * 10 / 36) + " " + i18n("m/s"));
    res = res.replace(QRegExp("\\%g"), getWindGust() ? QString("(") + i18n("gust ") + number(getWindGust()) + i18n(getUS()) + QString(")") : QString(""));
    res = res.replace(QRegExp("\\%y"), getWindGust() ? QString("(") + i18n("gust ") + number(getWindGust() * 10 / 36) + QString(" ") + i18n("m/s") + QString(")") : QString(""));
    res = res.replace(QRegExp("\\%p"), number(getPressure()) + " " + i18n(getUP()));
    res = res.replace(QRegExp("\\%a"), number(getPressure() * 75 / 100));
    res = res.replace(QRegExp("\\%q"), i18n("weather", getPressureD()));
    res = res.replace(QRegExp("\\%l"), getLocation());
    res = res.replace(QRegExp("\\%b"), i18n("weather", getWind()));
    res = res.replace(QRegExp("\\%u"), updated);
    res = res.replace(QRegExp("\\%r"), sun_raise);
    res = res.replace(QRegExp("\\%s"), sun_set);
    res = res.replace(QRegExp("\\%c"), i18n_conditions(getConditions()));
    res = res.replace(QRegExp("\\%v"), i18n("weather", getVisibility()) + (atol(getVisibility()) ? QString(" ") + i18n(getUD()) : QString("")));
    res = res.replace(QRegExp("\\%i"), number(getIcon()));
    return res;
}
Beispiel #9
0
void EarthquakeSet::loadANSSFile(const char* earthquakeFileName,double scaleFactor)
	{
	/* Open the input file: */
	Misc::File earthquakeFile(earthquakeFileName,"rt");
	
	/* Skip the two header lines: */
	char line[256];
	for(int i=0;i<2;++i)
		earthquakeFile.gets(line,sizeof(line));
	
	/* Read the rest of the file: */
	while(!earthquakeFile.eof())
		{
		/* Read the next line: */
		earthquakeFile.gets(line,sizeof(line));
		
		/* Skip empty lines: */
		if(line[0]=='\0'||line[0]=='\n')
			continue;
		
		/* Parse an event from the line: */
		Event e;
		
		/* Read date and time: */
		line[10]='\0';
		line[22]='\0';
		e.time=parseDateTime(line+0,line+11);
		
		/* Read event position: */
		float sphericalCoordinates[3];
		
		/* Read latitude: */
		line[31]='\0';
		sphericalCoordinates[0]=Math::rad(float(atof(line+23)));
		
		/* Read longitude: */
		line[41]='\0';
		sphericalCoordinates[1]=Math::rad(float(atof(line+32)));
		
		/* Read depth: */
		line[48]='\0';
		sphericalCoordinates[2]=float(atof(line+42));
		
		/* Convert the spherical position to Cartesian: */
		calcDepthPos<float>(sphericalCoordinates[0],sphericalCoordinates[1],sphericalCoordinates[2]*1000.0f,scaleFactor,e.position.getComponents());
		
		/* Read magnitude: */
		line[54]='\0';
		e.magnitude=float(atof(line+49));
		
		/* Save the event: */
		events.push_back(e);
		}
	}
Beispiel #10
0
TimeVal::TimeVal (const std::string &s, const parseformat fmt)
{
  struct tm conv;
  time_t    res;

  memset(&parser_context,0,sizeof(parser_context));

  reset();
  setBuffer(s);
  initParser();

  switch (fmt) {
  case XML_DATETIME:
    parseDateTime();
    break;
  case XML_DURATION:
    parseDuration();
    break;
  default:
    throw TimeValException("unknown XML TimeVal format");
    break;
  }

  xmlnormalize();
  memset(&conv,0,sizeof(conv));
  conv.tm_sec = parser_context.fValue[Second];
  conv.tm_min = parser_context.fValue[Minute];
  conv.tm_hour= parser_context.fValue[Hour];
  conv.tm_mday= parser_context.fValue[Day];
  if (parser_context.fValue[Month] > 0) {
    conv.tm_mon = parser_context.fValue[Month]-1;
  }
  conv.tm_year = parser_context.fValue[CentYear];
  if (conv.tm_year > 1900)
    conv.tm_year -= 1900;
  conv.tm_isdst = 0;

  if (fmt == XML_DURATION) {
    conv.tm_year += 70; // start of epoch added to the duration
    conv.tm_mday += 1;
    conv.tm_hour += 1;
  }

  tv_sec = mktime (&conv);
  tv_usec = parser_context.fValue[MiliSecond] * 1000;
  m_tz = gmt;

  // not give we get here, destructor does same thing to be sure
}
Beispiel #11
0
CommandBase* ParserList::makeCmdListString(string str) {
    ptime parsedDateTime = parseDateTime(str);
    if (!parsedDateTime.is_not_a_date_time()) {
        return makeCmdListDateTime(parsedDateTime);
    }
    CommandBase* parsedCommand = makeCmdListPeriod(str);
    if (parsedCommand != NULL) {
        return parsedCommand;
    }

    parsedCommand = makeCmdListSpecificMonth(str);
    if (parsedCommand != NULL) {
        return parsedCommand;
    } else {
        return makeCmdListSearchTerm(str);
    }
}
Beispiel #12
0
bool GoogleCalHandler::startElement( const QString & namespaceURI, const QString & localName, const QString & qName, const QXmlAttributes & atts )
{
    Q_UNUSED(namespaceURI);
    Q_UNUSED(localName);

    // if we are in a tree we dont' recognize, ignore the lot of it.
    if (ignoreDepth) {
        ignoreDepth++;
        return true;
    }

    Element t = token(qName);
    switch(t) {
        case Entry:
            state = EntryState;
            break;
        case Feed:
            state = FeedState;
            break;
        case Category:
            if (atts.value("scheme").endsWith("#kind")
                    && atts.value("term").endsWith("#event"))
                state = EventState;
            // TODO other kinds of categories?
            break;
        case Status:
            // this is how deleted events are detected
            if (atts.value("value").endsWith("#event.canceled"))  {
                removeCurrentAppointment = true;
            }
            break;
        case Reminder:
            if (!atts.value("minutes").isEmpty()) {
                lastAppointment.setAlarm(atts.value("minutes").toInt(), QAppointment::Visible);
            } else if (!atts.value("hours").isEmpty()) {
                lastAppointment.setAlarm(atts.value("minutes").toInt()*60, QAppointment::Visible);
            }
            // TODO doesn't handle days or absolute time.
            break;
        case When:
            {
                QString st = atts.value("startTime");
                QString et = atts.value("endTime");
                if (st.isEmpty() || et.isEmpty()) {
                    ignoreDepth++;
                } else {
                    QTimeZone tz = parseTimeZone(st);
                    QDateTime start = parseDateTime(st, tz);
                    QDateTime end = parseDateTime(et, tz);
                    if (st.length() < 19)
                        lastAppointment.setAllDay(true);
                    lastAppointment.setTimeZone(tz);
                    lastAppointment.setStart(start);
                    lastAppointment.setEnd(end);
                }
            }
            break;
        case Where:
            lastAppointment.setLocation(atts.value("valueString"));
            break;
        case Title:
        case Content:
            if (atts.value("type") != "text") {
                ignoreDepth++;
            }
            break;
        case Recurrence:
        case Id:
        case Published:
        case Updated:
            if (state != EntryState && state != EventState) {
                ignoreDepth++;
                break;
            }
            break;
        case Unrecognized:
            ignoreDepth++;
    }
    return true;
}
Beispiel #13
0
void parseVariant(proto_tree *tree, tvbuff_t *tvb, gint *pOffset, const char *szFieldName)
{
    proto_item *ti = proto_tree_add_text(tree, tvb, *pOffset, -1, "%s: Variant", szFieldName);
    proto_tree *subtree = proto_item_add_subtree(ti, ett_opcua_variant);
    gint    iOffset = *pOffset;
    guint8  EncodingMask;
    gint32  ArrayDimensions = 0;

    EncodingMask = tvb_get_guint8(tvb, iOffset);
    proto_tree_add_item(subtree, hf_opcua_variant_encodingmask, tvb, iOffset, 1, ENC_LITTLE_ENDIAN);
    iOffset++;

    if (EncodingMask & VARIANT_ARRAYMASK)
    {
        /* type is encoded in bits 0-5 */
        switch(EncodingMask & 0x3f)
        {
        case OpcUaType_Null: break;
        case OpcUaType_Boolean: parseArraySimple(subtree, tvb, &iOffset, hf_opcua_Boolean, parseBoolean); break;
        case OpcUaType_SByte: parseArraySimple(subtree, tvb, &iOffset, hf_opcua_SByte, parseSByte); break;
        case OpcUaType_Byte: parseArraySimple(subtree, tvb, &iOffset, hf_opcua_Byte, parseByte); break;
        case OpcUaType_Int16: parseArraySimple(subtree, tvb, &iOffset, hf_opcua_Int16, parseInt16); break;
        case OpcUaType_UInt16: parseArraySimple(subtree, tvb, &iOffset, hf_opcua_UInt16, parseUInt16); break;
        case OpcUaType_Int32: parseArraySimple(subtree, tvb, &iOffset, hf_opcua_Int32, parseInt32); break;
        case OpcUaType_UInt32: parseArraySimple(subtree, tvb, &iOffset, hf_opcua_UInt32, parseUInt32); break;
        case OpcUaType_Int64: parseArraySimple(subtree, tvb, &iOffset, hf_opcua_Int64, parseInt64); break;
        case OpcUaType_UInt64: parseArraySimple(subtree, tvb, &iOffset, hf_opcua_UInt64, parseUInt64); break;
        case OpcUaType_Float: parseArraySimple(subtree, tvb, &iOffset, hf_opcua_Float, parseFloat); break;
        case OpcUaType_Double: parseArraySimple(subtree, tvb, &iOffset, hf_opcua_Double, parseDouble); break;
        case OpcUaType_String: parseArraySimple(subtree, tvb, &iOffset, hf_opcua_String, parseString); break;
        case OpcUaType_DateTime: parseArraySimple(subtree, tvb, &iOffset, hf_opcua_DateTime, parseDateTime); break;
        case OpcUaType_Guid: parseArraySimple(subtree, tvb, &iOffset, hf_opcua_Guid, parseGuid); break;
        case OpcUaType_ByteString: parseArraySimple(subtree, tvb, &iOffset, hf_opcua_ByteString, parseByteString); break;
        case OpcUaType_XmlElement: parseArraySimple(subtree, tvb, &iOffset, hf_opcua_XmlElement, parseXmlElement); break;
        case OpcUaType_NodeId: parseArrayComplex(subtree, tvb, &iOffset, "NodeId", parseNodeId); break;
        case OpcUaType_ExpandedNodeId: parseArrayComplex(subtree, tvb, &iOffset, "ExpandedNodeId", parseExpandedNodeId); break;
        case OpcUaType_StatusCode: parseArraySimple(subtree, tvb, &iOffset, hf_opcua_StatusCode, parseStatusCode); break;
        case OpcUaType_DiagnosticInfo: parseArrayComplex(subtree, tvb, &iOffset, "DiagnosticInfo", parseDiagnosticInfo); break;
        case OpcUaType_QualifiedName: parseArrayComplex(subtree, tvb, &iOffset, "QualifiedName", parseQualifiedName); break;
        case OpcUaType_LocalizedText: parseArrayComplex(subtree, tvb, &iOffset, "LocalizedText", parseLocalizedText); break;
        case OpcUaType_ExtensionObject: parseArrayComplex(subtree, tvb, &iOffset, "ExtensionObject", parseExtensionObject); break;
        case OpcUaType_DataValue: parseArrayComplex(subtree, tvb, &iOffset, "DataValue", parseDataValue); break;
        case OpcUaType_Variant: parseArrayComplex(subtree, tvb, &iOffset, "Variant", parseVariant); break;
        }

        if (EncodingMask & VARIANT_ARRAYDIMENSIONS)
        {
            proto_item *ti_2 = proto_tree_add_text(subtree, tvb, iOffset, -1, "ArrayDimensions");
            proto_tree *subtree_2 = proto_item_add_subtree(ti_2, ett_opcua_array);
            int i;

            /* read array length */
            ArrayDimensions = tvb_get_letohl(tvb, iOffset);
            proto_tree_add_item(subtree_2, hf_opcua_ArraySize, tvb, iOffset, 4, ENC_LITTLE_ENDIAN);

            if (ArrayDimensions > MAX_ARRAY_LEN)
            {
                proto_item *pi;
                pi = proto_tree_add_text(subtree_2, tvb, iOffset, 4, "ArrayDimensions length %d too large to process", ArrayDimensions);
                PROTO_ITEM_SET_GENERATED(pi);
                return;
            }

            iOffset += 4;
            for (i=0; i<ArrayDimensions; i++)
            {
                parseInt32(subtree_2, tvb, &iOffset, hf_opcua_Int32);
            }
            proto_item_set_end(ti_2, tvb, iOffset);
        }
    }
    else
    {
        /* type is encoded in bits 0-5 */
        switch(EncodingMask & 0x3f)
        {
        case OpcUaType_Null: break;
        case OpcUaType_Boolean: parseBoolean(subtree, tvb, &iOffset, hf_opcua_Boolean); break;
        case OpcUaType_SByte: parseSByte(subtree, tvb, &iOffset, hf_opcua_SByte); break;
        case OpcUaType_Byte: parseByte(subtree, tvb, &iOffset, hf_opcua_Byte); break;
        case OpcUaType_Int16: parseInt16(subtree, tvb, &iOffset, hf_opcua_Int16); break;
        case OpcUaType_UInt16: parseUInt16(subtree, tvb, &iOffset, hf_opcua_UInt16); break;
        case OpcUaType_Int32: parseInt32(subtree, tvb, &iOffset, hf_opcua_Int32); break;
        case OpcUaType_UInt32: parseUInt32(subtree, tvb, &iOffset, hf_opcua_UInt32); break;
        case OpcUaType_Int64: parseInt64(subtree, tvb, &iOffset, hf_opcua_Int64); break;
        case OpcUaType_UInt64: parseUInt64(subtree, tvb, &iOffset, hf_opcua_UInt64); break;
        case OpcUaType_Float: parseFloat(subtree, tvb, &iOffset, hf_opcua_Float); break;
        case OpcUaType_Double: parseDouble(subtree, tvb, &iOffset, hf_opcua_Double); break;
        case OpcUaType_String: parseString(subtree, tvb, &iOffset, hf_opcua_String); break;
        case OpcUaType_DateTime: parseDateTime(subtree, tvb, &iOffset, hf_opcua_DateTime); break;
        case OpcUaType_Guid: parseGuid(subtree, tvb, &iOffset, hf_opcua_Guid); break;
        case OpcUaType_ByteString: parseByteString(subtree, tvb, &iOffset, hf_opcua_ByteString); break;
        case OpcUaType_XmlElement: parseXmlElement(subtree, tvb, &iOffset, hf_opcua_XmlElement); break;
        case OpcUaType_NodeId: parseNodeId(subtree, tvb, &iOffset, "Value"); break;
        case OpcUaType_ExpandedNodeId: parseExpandedNodeId(subtree, tvb, &iOffset, "Value"); break;
        case OpcUaType_StatusCode: parseStatusCode(subtree, tvb, &iOffset, hf_opcua_StatusCode); break;
        case OpcUaType_DiagnosticInfo: parseDiagnosticInfo(subtree, tvb, &iOffset, "Value"); break;
        case OpcUaType_QualifiedName: parseQualifiedName(subtree, tvb, &iOffset, "Value"); break;
        case OpcUaType_LocalizedText: parseLocalizedText(subtree, tvb, &iOffset, "Value"); break;
        case OpcUaType_ExtensionObject: parseExtensionObject(subtree, tvb, &iOffset, "Value"); break;
        case OpcUaType_DataValue: parseDataValue(subtree, tvb, &iOffset, "Value"); break;
        case OpcUaType_Variant: parseVariant(subtree, tvb, &iOffset, "Value"); break;
        }
    }

    proto_item_set_end(ti, tvb, iOffset);
    *pOffset = iOffset;
}
Beispiel #14
0
/**
 * @brief Rss 2.0 parsing
 * @param xml input string
 * @param data output data
 */
void Rss20Parser::parseRss(const QString& xml, QList<TRssItem>& data){
    QXmlStreamReader rd(xml);

    //support variables
    QString elemName;
    TRssChanel channel;
    TRssItem item;
    int state = 0;

    //default channel values
    channel.desc = QString();
    channel.link = QString();
    channel.title = QString();
    channel.version = Rss20;
    channel.image.link = QString();
    channel.image.title = QString();
    channel.image.url = QString();

    //parsing file
    while(!rd.atEnd()){
        switch(rd.readNext()){
            case QXmlStreamReader::StartElement:
                elemName = rd.name().toString();
                //image parsing
                if(state == 0 && elemName == "image"){
                    state = 1;
                }
                //item parsing
                else if(state == 0 && elemName == "item"){
                    //empty item
                    item.desc = QString();
                    item.dt = QDateTime();
                    item.guid = QString();
                    item.link = QString();
                    item.channel = channel;
                    item.title = QString();
                    //state for item parsing
                    state = 2;
                }
                break;

            case QXmlStreamReader::EndElement:
                elemName = "";
                //image parsing
                if(rd.name() == "image"){
                    state = 0;
                }
                //item parsing
                else if(rd.name() == "item"){
                    data.append(item);
                    state = 0;
                }
                break;

            case QXmlStreamReader::Characters:
                if(elemName.isEmpty()) break;
                //channel description
                if(state == 0){
                    if(elemName == "description") channel.desc = rd.text().toString().trimmed(); else
                    if(elemName == "link") channel.link = rd.text().toString(); else
                    if(elemName == "title") channel.title = rd.text().toString();
                }
                //channel image
                if(state == 1){
                    if(elemName == "title") channel.image.title = rd.text().toString(); else
                    if(elemName == "link") channel.image.link = rd.text().toString(); else
                    if(elemName == "url") channel.image.url = rd.text().toString();
                }
                //item parsing
                if(state == 2){
                    if(elemName == "title") item.title = rd.text().toString(); else
                    if(elemName == "description") item.desc = rd.text().toString(); else
                    if(elemName == "link") item.link = rd.text().toString(); else
                    if(elemName == "guid") item.guid = rd.text().toString(); else
                    if(elemName == "pubDate") item.dt = parseDateTime(rd.text().toString());
                }

            default:
                break;
        }
    }
}
MtpResponseCode MtpServer::doSendObjectInfo() {
    MtpString path;
    MtpStorageID storageID = mRequest.getParameter(1);
    MtpStorage* storage = getStorage(storageID);
    MtpObjectHandle parent = mRequest.getParameter(2);
    if (!storage)
        return MTP_RESPONSE_INVALID_STORAGE_ID;

    // special case the root
    if (parent == MTP_PARENT_ROOT) {
        path = storage->getPath();
        parent = 0;
    } else {
        int64_t length;
        MtpObjectFormat format;
        int result = mDatabase->getObjectFilePath(parent, path, length, format);
        if (result != MTP_RESPONSE_OK)
            return result;
        if (format != MTP_FORMAT_ASSOCIATION)
            return MTP_RESPONSE_INVALID_PARENT_OBJECT;
    }

    // read only the fields we need
    mData.getUInt32();  // storage ID
    MtpObjectFormat format = mData.getUInt16();
    mData.getUInt16();  // protection status
    mSendObjectFileSize = mData.getUInt32();
    mData.getUInt16();  // thumb format
    mData.getUInt32();  // thumb compressed size
    mData.getUInt32();  // thumb pix width
    mData.getUInt32();  // thumb pix height
    mData.getUInt32();  // image pix width
    mData.getUInt32();  // image pix height
    mData.getUInt32();  // image bit depth
    mData.getUInt32();  // parent
    uint16_t associationType = mData.getUInt16();
    uint32_t associationDesc = mData.getUInt32();   // association desc
    mData.getUInt32();  // sequence number
    MtpStringBuffer name, created, modified;
    mData.getString(name);    // file name
    mData.getString(created);      // date created
    mData.getString(modified);     // date modified
    // keywords follow

    LOGV("name: %s format: %04X\n", (const char *)name, format);
    time_t modifiedTime;
    if (!parseDateTime(modified, modifiedTime))
        modifiedTime = 0;

    if (path[path.size() - 1] != '/')
        path += "/";
    path += (const char *)name;

    // check space first
    if (mSendObjectFileSize > storage->getFreeSpace())
        return MTP_RESPONSE_STORAGE_FULL;
    uint64_t maxFileSize = storage->getMaxFileSize();
    // check storage max file size
    if (maxFileSize != 0) {
        // if mSendObjectFileSize is 0xFFFFFFFF, then all we know is the file size
        // is >= 0xFFFFFFFF
        if (mSendObjectFileSize > maxFileSize || mSendObjectFileSize == 0xFFFFFFFF)
            return MTP_RESPONSE_OBJECT_TOO_LARGE;
    }

LOGD("path: %s parent: %d storageID: %08X", (const char*)path, parent, storageID);
    MtpObjectHandle handle = mDatabase->beginSendObject((const char*)path,
            format, parent, storageID, mSendObjectFileSize, modifiedTime);
    if (handle == kInvalidObjectHandle) {
        return MTP_RESPONSE_GENERAL_ERROR;
    }

  if (format == MTP_FORMAT_ASSOCIATION) {
        mode_t mask = umask(0);
        int ret = mkdir((const char *)path, mDirectoryPermission);
        umask(mask);
        if (ret && ret != -EEXIST)
            return MTP_RESPONSE_GENERAL_ERROR;
        chown((const char *)path, getuid(), mFileGroup);

        // SendObject does not get sent for directories, so call endSendObject here instead
        mDatabase->endSendObject(path, handle, MTP_FORMAT_ASSOCIATION, MTP_RESPONSE_OK);
    } else {
        mSendObjectFilePath = path;
        // save the handle for the SendObject call, which should follow
        mSendObjectHandle = handle;
        mSendObjectFormat = format;
    }

    mResponse.setParameter(1, storageID);
    mResponse.setParameter(2, parent);
    mResponse.setParameter(3, handle);

    return MTP_RESPONSE_OK;
}
Beispiel #16
0
void EarthquakeSet::loadCSVFile(const char* earthquakeFileName,double scaleFactor)
	{
	/* Open the input file: */
	Threads::GzippedFileCharacterSource earthquakeFile(earthquakeFileName);
	Misc::ValueSource source(earthquakeFile);
	source.setPunctuation(",\n");
	source.setQuotes("\"");
	source.skipWs();
	
	/*********************************************************************
	Parse the point file's header line:
	*********************************************************************/
	
	/* Remember the column indices of important columns: */
	int latIndex=-1;
	int lngIndex=-1;
	int radiusIndex=-1;
	enum RadiusMode // Enumerated types for radius coordinate modes
		{
		RADIUS,DEPTH,NEGDEPTH
		} radiusMode=RADIUS;
	int dateIndex=-1;
	int timeIndex=-1;
	int magIndex=-1;
	
	/* Read the header line's columns: */
	int column=0;
	while(true)
		{
		/* Read the next column header: */
		std::string header=!source.eof()&&source.peekc()!='\n'&&source.peekc()!=','?source.readString():"";
		
		/* Parse the column header: */
		if(strequal(header,"Latitude")||strequal(header,"Lat"))
			latIndex=column;
		else if(strequal(header,"Longitude")||strequal(header,"Long")||strequal(header,"Lon"))
			lngIndex=column;
		else if(strequal(header,"Radius"))
			{
			radiusIndex=column;
			radiusMode=RADIUS;
			}
		else if(strequal(header,"Depth"))
			{
			radiusIndex=column;
			radiusMode=DEPTH;
			}
		else if(strequal(header,"Negative Depth")||strequal(header,"Neg Depth")||strequal(header,"NegDepth"))
			{
			radiusIndex=column;
			radiusMode=NEGDEPTH;
			}
		else if(strequal(header,"Date"))
			dateIndex=column;
		else if(strequal(header,"Time"))
			timeIndex=column;
		else if(strequal(header,"Magnitude")||strequal(header,"Mag"))
			magIndex=column;
		
		++column;
		
		/* Check for end of line: */
		if(source.eof()||source.peekc()=='\n')
			break;
		
		/* Skip an optional comma: */
		if(source.peekc()==',')
			source.skipString();
		}
	
	/* Determine the number of fields: */
	int maxIndex=latIndex;
	if(maxIndex<lngIndex)
		maxIndex=lngIndex;
	if(maxIndex<radiusIndex)
		maxIndex=radiusIndex;
	if(maxIndex<dateIndex)
		maxIndex=dateIndex;
	if(maxIndex<timeIndex)
		maxIndex=timeIndex;
	if(maxIndex<magIndex)
		maxIndex=magIndex;
	
	/* Skip the newline: */
	source.skipLine();
	source.skipWs();
	
	/* Check if all required portions have been detected: */
	if(latIndex<0||lngIndex<0||radiusIndex<0||dateIndex<0||timeIndex<0||magIndex<0)
		Misc::throwStdErr("EarthquakeSet::EarthquakeSet: Missing earthquake components in input file %s",earthquakeFileName);
	
	/* Read lines from the file: */
	int lineNumber=2;
	while(!source.eof())
		{
		float sphericalCoordinates[3]={0.0f,0.0f,0.0f};
		std::string date,time;
		float magnitude=0.0f;
		int column=0;
		try
			{
			while(true)
				{
				/* Read the next field: */
				if(!source.eof()&&source.peekc()!='\n'&&source.peekc()!=',')
					{
					if(column==latIndex)
						sphericalCoordinates[0]=Math::rad(float(source.readNumber()));
					else if(column==lngIndex)
						sphericalCoordinates[1]=Math::rad(float(source.readNumber()));
					else if(column==radiusIndex)
						sphericalCoordinates[2]=float(source.readNumber());
					else if(column==dateIndex)
						date=source.readString();
					else if(column==timeIndex)
						time=source.readString();
					else if(column==magIndex)
						magnitude=float(source.readNumber());
					else
						source.skipString();
					}
				
				++column;
				
				/* Check for end of line: */
				if(source.eof()||source.peekc()=='\n')
					break;
				
				/* Skip an optional comma: */
				if(source.peekc()==',')
					source.skipString();
				}
			}
		catch(Misc::ValueSource::NumberError err)
			{
			/* Ignore the error and the malformed event */
			}
		
		/* Skip the newline: */
		source.skipLine();
		source.skipWs();
		
		/* Check if all fields were read: */
		if(column>maxIndex)
			{
			/* Create an event: */
			Event e;
			
			/* Convert the read spherical coordinates to Cartesian coordinates: */
			switch(radiusMode)
				{
				case RADIUS:
					calcRadiusPos<float>(sphericalCoordinates[0],sphericalCoordinates[1],sphericalCoordinates[2]*1000.0f,scaleFactor,e.position.getComponents());
					break;
				
				case DEPTH:
					calcDepthPos<float>(sphericalCoordinates[0],sphericalCoordinates[1],sphericalCoordinates[2]*1000.0f,scaleFactor,e.position.getComponents());
					break;
				
				case NEGDEPTH:
					calcDepthPos<float>(sphericalCoordinates[0],sphericalCoordinates[1],-sphericalCoordinates[2]*1000.0f,scaleFactor,e.position.getComponents());
					break;
				}
			
			/* Calculate the event time: */
			e.time=parseDateTime(date.c_str(),time.c_str());
			
			/* Store the event magnitude: */
			e.magnitude=magnitude;
			
			/* Append the event to the earthquake set: */
			events.push_back(e);
			}
		
		++lineNumber;
		}
	}
Beispiel #17
0
String Locale::parseDateTime(const DateTime& dateTime,
                             DateFormatOptions options) const
{ return parseDateTime(dateTime,
                       Locale::LongDate,
                       Locale::HoursMinutes,
                       options); }
Beispiel #18
0
bool Timestamp::parse(const std::string& str, Timestamp& t) {
    return parseDateTime(str.c_str(), t.value);
}
Beispiel #19
0
bool GoogleCalHandler::endElement( const QString & namespaceURI, const QString & localName, const QString & qName )
{
    Q_UNUSED(namespaceURI);
    Q_UNUSED(localName);

    if (ignoreDepth) {
        ignoreDepth--;
        Q_ASSERT(ignoreDepth >= 0);
        return true;
    }
    Element t = token(qName);
    switch(t) {
        case Entry:
            if (removeCurrentAppointment) {
                mRemoved.append(lastAppointment.uid());
                removeCurrentAppointment = false;
            } else {
                mAppointments.append(lastAppointment);
            }
            lastAppointment = QAppointment();
            state = FeedState;
            break;
        case Feed:
            state = StartState;
        case Title:
            if (state == FeedState)
                mName = lastText;
            else
                lastAppointment.setDescription(lastText);
            break;
        case Content:
            lastAppointment.setNotes(lastText);
            break;
        case Recurrence:
            {
            // this is the MAIN TODO, seeing as once this works,
                /*
                   iCal format, is not compatible with vcard parsing.
                   however it may be similar enough that we can still use existing vcard
                   parser.

                   NOTE: RRULE format is different in iCal to vCard
               */
            /* Example RRULE text from recurrence section.
               can be given instead of when
               e.g.
                DTSTART;TZID=Australia/Brisbane:20060615T113000
                DURATION:PT1800S
                RRULE:FREQ=WEEKLY;INTERVAL=2;BYDAY=TH

                BEGIN:VTIMEZONE
                TZID:Australia/Brisbane
                X-LIC-LOCATION:Australia/Brisbane
                BEGIN:STANDARD
                TZOFFSETFROM:+1000
                TZOFFSETTO:+1000
                TZNAME:EST
                DTSTART:19700101T000000
                END:STANDARD
                END:VTIMEZONE
             */

                // pad out data to make it look like a vcal and get through our parser
                // qappointment also has some special ical handling in it.
                QByteArray data = "BEGIN:VCALENDAR\r\nVERSION:1.0\r\nBEGIN:VEVENT\r\n"
                    + lastText.toUtf8() + "END:VEVENT\r\nEND:VCALENDAR\r\n";

                QList<QAppointment> result = QAppointment::readVCalendarData(data.constData(), data.length());
                if (result.count() > 0) {
                    QAppointment a = result[0];
                    lastAppointment.setStart(a.start());
                    lastAppointment.setEnd(a.end());
                    lastAppointment.setRepeatRule(a.repeatRule());
                    lastAppointment.setFrequency(a.frequency());
                    lastAppointment.setRepeatUntil(a.repeatUntil());
                    lastAppointment.setWeekFlags(a.weekFlags());
                }
            }
            break;
        case Id:
            {
                QUniqueId u = parseId(lastText + mIdContext);
                lastAppointment.setUid(u);
                // a lot more redundency in a google id.
                lastAppointment.setCustomField("GoogleId", lastText);
            }
            break;
        case Published:
            {
                // TODO should support published/updated fields natively in PimRecords?
                QDateTime dt = parseDateTime(lastText, QTimeZone::utc());
                lastAppointment.setCustomField("GooglePublished", dt.toString(Qt::ISODate));
            }
            break;
        case Updated:
            {
                QDateTime dt = parseDateTime(lastText, QTimeZone::utc());
                lastAppointment.setCustomField("GoogleUpdated", dt.toString(Qt::ISODate));
            }
            break;
        case Category:
        case Reminder:
        case When:
        case Where:
        case Status:
            break;
        case Unrecognized:
            break;

    }
    return true;
}
Beispiel #20
0
void GourceSettings::importGourceSettings(ConfFile& conffile, ConfSection* gource_settings) {

    setGourceDefaults();

    if(gource_settings == 0) gource_settings = conffile.getSection(default_section_name);

    if(gource_settings == 0) {
        gource_settings = conffile.addSection("gource");
    }

    ConfEntry* entry = 0;

    //hide flags

    std::vector<std::string> hide_fields;

    if((entry = gource_settings->getEntry("hide")) != 0) {

        if(!entry->hasValue()) conffile.missingValueException(entry);

        std::string hide_string = entry->getString();

        size_t sep;
        while((sep = hide_string.find(",")) != std::string::npos) {

            if(sep == 0 && hide_string.size()==1) break;

            if(sep == 0) {
                hide_string = hide_string.substr(sep+1, hide_string.size()-1);
                continue;
            }

            std::string hide_field  = hide_string.substr(0, sep);
            hide_fields.push_back(hide_field);
            hide_string = hide_string.substr(sep+1, hide_string.size()-1);
        }

        if(hide_string.size() > 0 && hide_string != ",") hide_fields.push_back(hide_string);

        //validate field list

        for(std::vector<std::string>::iterator it = hide_fields.begin(); it != hide_fields.end(); it++) {
            std::string hide_field = (*it);

            if(   hide_field != "date"
               && hide_field != "users"
               && hide_field != "tree"
               && hide_field != "files"
               && hide_field != "usernames"
               && hide_field != "filenames"
               && hide_field != "dirnames"
               && hide_field != "bloom"
               && hide_field != "progress"
               && hide_field != "mouse"
               && hide_field != "root") {
                std::string unknown_hide_option = std::string("unknown option hide ") + hide_field;
                conffile.entryException(entry, unknown_hide_option);
            }
        }
    }

    //check hide booleans
    for(std::map<std::string,std::string>::iterator it = arg_types.begin(); it != arg_types.end(); it++) {
        if(it->first.find("hide-") == 0 && it->second == "bool") {

            if(gource_settings->getBool(it->first)) {
                std::string hide_field = it->first.substr(5, it->first.size()-5);
                hide_fields.push_back(hide_field);
            }
        }
    }

    if(hide_fields.size()>0) {

        for(std::vector<std::string>::iterator it = hide_fields.begin(); it != hide_fields.end(); it++) {
            std::string hidestr = (*it);

                if(hidestr == "date")       hide_date      = true;
            else if(hidestr == "users")     hide_users     = true;
            else if(hidestr == "tree")      hide_tree      = true;
            else if(hidestr == "files")     hide_files     = true;
            else if(hidestr == "usernames") hide_usernames = true;
            else if(hidestr == "filenames") hide_filenames = true;
            else if(hidestr == "dirnames")  hide_dirnames  = true;
            else if(hidestr == "bloom")     hide_bloom     = true;
            else if(hidestr == "progress")  hide_progress  = true;
            else if(hidestr == "root")      hide_root      = true;
            else if(hidestr == "mouse")     {
                hide_mouse     = true;
                hide_progress  = true;
            }
        }
    }

    if((entry = gource_settings->getEntry("date-format")) != 0) {

        if(!entry->hasValue()) conffile.missingValueException(entry);

        date_format = entry->getString();
    }

    if(gource_settings->getBool("disable-auto-rotate")) {
        disable_auto_rotate=true;
    }

    if(gource_settings->getBool("disable-auto-skip")) {
        auto_skip_seconds = -1.0;
    }

    if(gource_settings->getBool("loop")) {
        loop = true;
    }

    if((entry = gource_settings->getEntry("git-branch")) != 0) {

        if(!entry->hasValue()) conffile.missingValueException(entry);

        Regex branch_regex("^(?!-)[/\\w.,;_=+{}\\[\\]-]+$");

        std::string branch = entry->getString();

        if(branch_regex.match(branch)) {
            git_branch = branch;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if(gource_settings->getBool("colour-images")) {
        colour_user_images = true;
    }

    if((entry = gource_settings->getEntry("crop")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify crop (vertical,horizontal)");

        std::string crop = entry->getString();

        if(crop == "vertical") {
            crop_vertical = true;
        } else if (crop == "horizontal") {
            crop_horizontal = true;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("log-format")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify log-format (format)");

        log_format = entry->getString();

        if(log_format == "cvs") {
            conffile.entryException(entry, "please use either 'cvs2cl' or 'cvs-exp'");
        }

        if(   log_format != "git"
           && log_format != "cvs-exp"
           && log_format != "cvs2cl"
           && log_format != "svn"
           && log_format != "custom"
           && log_format != "hg"
           && log_format != "bzr"
           && log_format != "apache") {

            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("default-user-image")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify default-user-image (image path)");

        default_user_image = entry->getString();
    }

    if((entry = gource_settings->getEntry("user-image-dir")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-image-dir (directory)");

        user_image_dir = entry->getString();

        //append slash
        if(user_image_dir[user_image_dir.size()-1] != '/') {
            user_image_dir += std::string("/");
        }

        user_image_map.clear();

        boost::filesystem::path image_dir_path(user_image_dir);

        if(!is_directory(image_dir_path)) {
             conffile.entryException(entry, "specified user-image-dir is not a directory");
        }

        std::vector<boost::filesystem::path> image_dir_files;

        try {
            copy(boost::filesystem::directory_iterator(image_dir_path), boost::filesystem::directory_iterator(), back_inserter(image_dir_files));
        } catch(const boost::filesystem::filesystem_error& exception) {
             conffile.entryException(entry, "error reading specified user-image-dir");
        }

        for(boost::filesystem::path& p : image_dir_files) {

            std::string dirfile;

#ifdef _WIN32
            std::wstring dirfile_16 = p.filename().wstring();
            utf8::utf16to8(dirfile_16.begin(), dirfile_16.end(), back_inserter(dirfile));
#else
            dirfile = p.filename().string();
#endif
            std::string file_ext = extension(p);
            boost::algorithm::to_lower(file_ext);

            if(file_ext != ".jpg" && file_ext != ".jpeg" && file_ext != ".png") continue;

            std::string image_path = gGourceSettings.user_image_dir + dirfile;
            std::string name       = dirfile.substr(0,dirfile.size() - file_ext.size());

#ifdef __APPLE__
                CFMutableStringRef help = CFStringCreateMutable(kCFAllocatorDefault, 0);
                CFStringAppendCString(help, name.c_str(), kCFStringEncodingUTF8);
                CFStringNormalize(help, kCFStringNormalizationFormC);
                char data[4096];
                CFStringGetCString(help,
                                   data,
                                   sizeof(data),
                                   kCFStringEncodingUTF8);
                name = data;
#endif

            debugLog("%s => %s", name.c_str(), image_path.c_str());

            user_image_map[name] = image_path;
        }
    }

    if((entry = gource_settings->getEntry("caption-file")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption file (filename)");

        caption_file = entry->getString();

        if(!boost::filesystem::exists(caption_file)) {
            conffile.entryException(entry, "caption file not found");
        }
    }

    if((entry = gource_settings->getEntry("caption-duration")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption duration (seconds)");

        caption_duration = entry->getFloat();

        if(caption_duration <= 0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("caption-size")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption size");

        caption_size = entry->getInt();

        if(caption_size<1 || caption_size>100) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("caption-offset")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption offset");

        caption_offset = entry->getInt();
    }

    if((entry = gource_settings->getEntry("caption-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            caption_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            caption_colour = vec3(r,g,b);
            caption_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("filename-colour")) != 0) {
        if(!entry->hasValue()) conffile.entryException(entry, "specify filename colour (FFFFFF)");

	int r,g,b;

	std::string colstring = entry->getString();

	if(entry->isVec3()) {
	    filename_colour = entry->getVec3();
	} else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            filename_colour = vec3(r,g,b);
            filename_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("filename-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify duration to keep files on screen (float)");

        filename_time = entry->getFloat();

        if(filename_time<2.0f) {
            conffile.entryException(entry, "filename-time must be >= 2.0");
        }
    }

    if((entry = gource_settings->getEntry("bloom-intensity")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify bloom-intensity (float)");

        bloom_intensity = entry->getFloat();

        if(bloom_intensity<=0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("bloom-multiplier")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify bloom-multiplier (float)");

        bloom_multiplier = entry->getFloat();

        if(bloom_multiplier<=0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("elasticity")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify elasticity (float)");

        elasticity = entry->getFloat();

        if(elasticity<=0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("font-size")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify font size");

        font_size = entry->getInt();

        if(font_size<1 || font_size>100) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("hash-seed")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify hash seed (integer)");

        gStringHashSeed = entry->getInt();
    }

    if((entry = gource_settings->getEntry("font-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify font colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            font_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            font_colour = vec3(r,g,b);
            font_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("background-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify background colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            background_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            background_colour = vec3(r,g,b);
            background_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("highlight-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify highlight colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            highlight_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            highlight_colour = vec3(r,g,b);
            highlight_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("selection-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify selection colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            selection_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            selection_colour = vec3(r,g,b);
            selection_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("dir-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify dir colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            dir_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            dir_colour = vec3(r,g,b);
            dir_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("background-image")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify background image (image path)");

        background_image = entry->getString();
    }

    if((entry = gource_settings->getEntry("title")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify title");

        title = entry->getString();
    }

    if((entry = gource_settings->getEntry("logo")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify logo (image path)");

        logo = entry->getString();
    }

    if((entry = gource_settings->getEntry("logo-offset")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify logo-offset (XxY)");

        std::string logo_offset_str = entry->getString();

        int posx = 0;
        int posy = 0;

        if(parseRectangle(logo_offset_str, posx, posy)) {
            logo_offset = vec2(posx, posy);
        } else {
            conffile.invalidValueException(entry);
        }

    }

    if((entry = gource_settings->getEntry("seconds-per-day")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify seconds-per-day (seconds)");

        float seconds_per_day = entry->getFloat();

        if(seconds_per_day<=0.0f) {
            conffile.invalidValueException(entry);
        }

        // convert seconds-per-day to days-per-second
        days_per_second = 1.0 / seconds_per_day;
    }

    if((entry = gource_settings->getEntry("auto-skip-seconds")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify auto-skip-seconds (seconds)");

        auto_skip_seconds = entry->getFloat();

        if(auto_skip_seconds <= 0.0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("file-idle-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify file-idle-time (seconds)");

        std::string file_idle_str = entry->getString();

        file_idle_time = (float) atoi(file_idle_str.c_str());

        if(file_idle_time<0.0f || (file_idle_time == 0.0f && file_idle_str[0] != '0') ) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("user-idle-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-idle-time (seconds)");

        user_idle_time = entry->getFloat();

        if(user_idle_time < 0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("time-scale")) != 0) {

        if(!entry->hasValue())
            conffile.entryException(entry, "specify time-scale (scale)");

        time_scale = entry->getFloat();

        if(time_scale <= 0.0f || time_scale > 4.0f) {
            conffile.entryException(entry, "time-scale outside of range 0.0 - 4.0");
        }
    }

    if((entry = gource_settings->getEntry("start-date")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify start-date (YYYY-MM-DD hh:mm:ss)");

        std::string start_date_string = entry->getString();

        if(parseDateTime(start_date_string, start_timestamp)) {

            char datestr[256];
            strftime(datestr, 256, "%Y-%m-%d", localtime ( &start_timestamp ));
            start_date = datestr;

        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("stop-date")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify stop-date (YYYY-MM-DD hh:mm:ss)");

        std::string end_date_string = entry->getString();

        if(parseDateTime(end_date_string, stop_timestamp)) {

            struct tm * timeinfo;
            timeinfo = localtime ( &stop_timestamp );

            time_t stop_timestamp_rounded = stop_timestamp;

            if(timeinfo->tm_hour > 0 || timeinfo->tm_min > 0 || timeinfo->tm_sec > 0) {
                stop_timestamp_rounded += 60*60*24;
            }

            char datestr[256];
            strftime(datestr, 256, "%Y-%m-%d", localtime ( &stop_timestamp_rounded ));
            stop_date = datestr;

        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("start-position")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify start-position (float,random)");

        if(entry->getString() == "random") {
            srand(time(0));
            start_position = (rand() % 1000) / 1000.0f;
        } else {
            start_position = entry->getFloat();

            if(start_position<=0.0 || start_position>=1.0) {
                conffile.entryException(entry, "start-position outside of range 0.0 - 1.0 (non-inclusive)");
            }
        }
    }

    if((entry = gource_settings->getEntry("stop-position")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify stop-position (float)");

        stop_position = entry->getFloat();

        if(stop_position<=0.0 || stop_position>1.0) {
            conffile.entryException(entry, "stop-position outside of range 0.0 - 1.0 (inclusive)");
        }
    }

    if((entry = gource_settings->getEntry("stop-at-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify stop-at-time (seconds)");

        stop_at_time = entry->getFloat();

        if(stop_at_time <= 0.0) {
            conffile.invalidValueException(entry);
        }
    }

    if(gource_settings->getBool("key")) {
        show_key = true;
    }

    if(gource_settings->getBool("ffp")) {
        ffp = true;
    }

    if(gource_settings->getBool("realtime")) {
        days_per_second = 1.0 / 86400.0;
    }

    if(gource_settings->getBool("no-time-travel")) {
        no_time_travel = true;
    }

    if(gource_settings->getBool("dont-stop")) {
        dont_stop = true;
    }

    if(gource_settings->getBool("stop-at-end")) {
        stop_at_end = true;
    }

    //NOTE: this no longer does anything
    if(gource_settings->getBool("stop-on-idle")) {
        stop_on_idle = true;
    }

    if((entry = gource_settings->getEntry("max-files")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify max-files (number)");

        max_files = entry->getInt();

        if( max_files<0 || (max_files == 0 && entry->getString() != "0") ) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("max-file-lag")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify max-file-lag (seconds)");

        max_file_lag = entry->getFloat();

        if(max_file_lag==0.0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("user-friction")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-friction (seconds)");

        user_friction = entry->getFloat();

        if(user_friction<=0.0) {
            conffile.invalidValueException(entry);
        }

        user_friction = 1.0 / user_friction;
    }

    if((entry = gource_settings->getEntry("user-scale")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-scale (scale)");

        user_scale = entry->getFloat();

        if(user_scale<=0.0 || user_scale>100.0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("max-user-speed")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify max-user-speed (units)");

        max_user_speed = entry->getFloat();

        if(max_user_speed<=0) {
            conffile.invalidValueException(entry);
        }
    }

    if(   gource_settings->getBool("highlight-users")
       || gource_settings->getBool("highlight-all-users")) {
        highlight_all_users = true;
    }

    if(gource_settings->getBool("highlight-dirs")) {
        highlight_dirs = true;
    }

    if((entry = gource_settings->getEntry("camera-mode")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify camera-mode (overview,track)");

        camera_mode = entry->getString();

        if(camera_mode != "overview" && camera_mode != "track") {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("padding")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify padding (float)");

        padding = entry->getFloat();

        if(padding <= 0.0f || padding >= 2.0f) {
            conffile.invalidValueException(entry);
        }
    }

    // multi-value entries

    if((entry = gource_settings->getEntry("highlight-user")) != 0) {

        ConfEntryList* highlight_user_entries = gource_settings->getEntries("highlight-user");

        for(ConfEntryList::iterator it = highlight_user_entries->begin(); it != highlight_user_entries->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify highlight-user (user)");

            highlight_users.push_back(entry->getString());
        }
    }

    if((entry = gource_settings->getEntry("follow-user")) != 0) {

        ConfEntryList* follow_user_entries = gource_settings->getEntries("follow-user");

        for(ConfEntryList::iterator it = follow_user_entries->begin(); it != follow_user_entries->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify follow-user (user)");

            follow_users.push_back(entry->getString());
        }
    }

    if(gource_settings->getBool("file-extensions")) {
        file_extensions=true;
    }

    if(gource_settings->getBool("file-extension-fallback")) {
        file_extension_fallback=true;
    }

    if((entry = gource_settings->getEntry("file-filter")) != 0) {

        ConfEntryList* filters = gource_settings->getEntries("file-filter");

        for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify file-filter (regex)");

            std::string filter_string = entry->getString();

            Regex* r = new Regex(filter_string, 1);

            if(!r->isValid()) {
                delete r;
                conffile.entryException(entry, "invalid file-filter regular expression");
            }

            file_filters.push_back(r);
        }
    }

    if((entry = gource_settings->getEntry("file-show-filter")) != 0) {

        ConfEntryList* filters = gource_settings->getEntries("file-show-filter");

        for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify file-show-filter (regex)");

            std::string filter_string = entry->getString();

            Regex* r = new Regex(filter_string, 1);

            if(!r->isValid()) {
                delete r;
                conffile.entryException(entry, "invalid file-show-filter regular expression");
            }

            file_show_filters.push_back(r);
        }
    }

    if((entry = gource_settings->getEntry("user-filter")) != 0) {

        ConfEntryList* filters = gource_settings->getEntries("user-filter");

        for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify user-filter (regex)");

            std::string filter_string = entry->getString();

            Regex* r = new Regex(filter_string, 1);

            if(!r->isValid()) {
                delete r;
                conffile.entryException(entry, "invalid user-filter regular expression");
            }

            user_filters.push_back(r);
        }
    }

    if((entry = gource_settings->getEntry("user-show-filter")) != 0) {

        ConfEntryList* filters = gource_settings->getEntries("user-show-filter");

        for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify user-show-filter (regex)");

            std::string filter_string = entry->getString();

            Regex* r = new Regex(filter_string, 1);

            if(!r->isValid()) {
                delete r;
                conffile.entryException(entry, "invalid user-show-filter regular expression");
            }

            user_show_filters.push_back(r);
        }
    }

    if((entry = gource_settings->getEntry("dir-name-depth")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify dir-name-depth (depth)");

        dir_name_depth = entry->getInt();

        if(dir_name_depth <= 0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("dir-name-position")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify dir-name-position (float)");

        dir_name_position = entry->getFloat();

        if(dir_name_position < 0.1f || dir_name_position > 1.0f) {
            conffile.entryException(entry, "dir-name-position outside of range 0.1 - 1.0 (inclusive)");
        }
    }

    //validate path
    if(gource_settings->hasValue("path")) {
        path = gource_settings->getString("path");
        default_path = false;
    }

    if(path == "-") {

        if(log_format.size() == 0) {
            throw ConfFileException("log-format required when reading from STDIN", "", 0);
        }

#ifdef _WIN32
        DWORD available_bytes;
        HANDLE stdin_handle = GetStdHandle(STD_INPUT_HANDLE);

        while(PeekNamedPipe(stdin_handle, 0, 0, 0,
            &available_bytes, 0) && available_bytes==0 && !std::cin.fail()) {
            SDL_Delay(100);
        }
#else
        while(std::cin.peek() == EOF && !std::cin.fail()) SDL_Delay(100);
#endif

        std::cin.clear();

    } else if(!path.empty() && path != ".") {

        //remove trailing slash
        if(path[path.size()-1] == '\\' || path[path.size()-1] == '/') {
            path.resize(path.size()-1);
        }

        // check path exists
        if(!boost::filesystem::exists(path)) {
            throw ConfFileException(str(boost::format("'%s' does not appear to be a valid file or directory") % path), "", 0);
        }
    }
}
Beispiel #21
0
void
QWebdavUrlInfo::davParsePropstats( const QString & path,
				   const QDomNodeList & propstats )
{
  QString mimeType;
  bool foundExecutable = false;
  bool isDirectory = false;

  setName(path);

  for ( int i = 0; i < propstats.count(); i++) {
    QDomElement propstat = propstats.item(i).toElement();
    QDomElement status = propstat.namedItem( "status" ).toElement();

    if ( status.isNull() ) {
      qDebug() << "Error, no status code in this propstat";
      return;
    }

    int code = codeFromResponse( status.text() );

    if (code == 404)
      continue ;

    QDomElement prop = propstat.namedItem( "prop" ).toElement();

    if ( prop.isNull() ) {
      qDebug() << "Error: no prop segment in this propstat.";
      return;
    }

    for ( QDomNode n = prop.firstChild(); !n.isNull(); n = n.nextSibling() ) {
      QDomElement property = n.toElement();

      if (property.isNull())
        continue;

      properties_[property.namespaceURI()][property.tagName()] = property.text();

      if ( property.namespaceURI() != "DAV:" ) {
	// break out - we're only interested in properties from the DAV namespace
	continue;
      }

      if ( property.tagName() == "creationdate" )
	setCreatedAt(parseDateTime( property.text(), property.attribute("dt") ));
      else if ( property.tagName() == "getcontentlength" )
        setSize(property.text().toULong());
      else if ( property.tagName() == "displayname" )
	setDisplayName(property.text());
      else if ( property.tagName() == "source" )
      {
        QDomElement source;

	source = property.namedItem( "link" ).toElement()
	  .namedItem( "dst" ).toElement();

        if ( !source.isNull() )
          setSource(source.text());
      }
      else if ( property.tagName() == "getcontentlanguage" )
	setContentLanguage(property.text());
      else if ( property.tagName() == "getcontenttype" )
	{
	  if ( property.text() == "httpd/unix-directory" )
	    isDirectory = true;
	  else
	    mimeType = property.text();
	}
      else if ( property.tagName() == "executable" )
	{
	  if ( property.text() == "T" )
	    foundExecutable = true;
	}
      else if ( property.tagName() == "getlastmodified" )
	setLastModified(parseDateTime( property.text(), property.attribute("dt") ));
      else if ( property.tagName() == "getetag" )
	setEntitytag(property.text());
      else if ( property.tagName() == "resourcetype" )
        {
	  if ( !property.namedItem( "collection" ).toElement().isNull() )
	    isDirectory = true;
	}
      else
        qDebug() << "Found unknown webdav property: "
		 << property.tagName() << property.text();
    }
  }
  setDir(isDirectory);
  setFile(!isDirectory);

  if (isDirectory && !name().endsWith("/"))
    setName(name() + "/");

  if ( foundExecutable || isDirectory )
    setPermissions(0700);
  else
    setPermissions(0600);

  if ( !isDirectory && !mimeType.isEmpty() )
    setMimeType(mimeType);
}
Beispiel #22
0
inline CDateTime Win32_OperatingSystem::LastBootUpTime() const
{
	return parseDateTime(getProperty<tstring>(TXT("LastBootUpTime")));
}
Beispiel #23
0
String Locale::parseDateTime(const DateTime& dateTime,
                             DateFormat dateFormat,
														 TimeFormat timeFormat,
                             int options) const
{
	String datePattern, timePattern, pattern;

	if (options & RelativeDays
	    && static_cast<Date>(dateTime)
	        == static_cast<Date>(DateTime::now().toLocal(dateTime.timeZone())))
	{
		datePattern = "aujourd’hui";
	}
	else if (options & RelativeDays
	         && static_cast<Date>(dateTime) <= static_cast<Date>(
	           DateTime::now().toLocal(dateTime.timeZone()) - "0000-00-01")
	         && static_cast<Date>(dateTime) > static_cast<Date>(
	           DateTime::now().toLocal(dateTime.timeZone()) - "0000-00-02"))
	{
		datePattern = "hier";
	}
	else if (options & RelativeDays
	         && static_cast<Date>(dateTime) >= static_cast<Date>(
	           DateTime::now().toLocal(dateTime.timeZone()) + "0000-00-01")
	         && static_cast<Date>(dateTime) < static_cast<Date>(
	           DateTime::now().toLocal(dateTime.timeZone()) + "0000-00-02"))
	{
		datePattern = "demain";
	}
	else
	{
		if (dateFormat == DigitalDate)
			datePattern = "%x";
		else if (dateFormat == ShortDate)
		{
			if (_datePosition == YMD)
				datePattern = "%Y %b %d";
			else if (_datePosition == MDY)
				datePattern = "%b %d %Y";
			else
				datePattern = "%d %b %Y";
		}
		else if (dateFormat == LongDate)
		{
			if (_datePosition == YMD)
				datePattern = "%Y %B %d";
			else if (_datePosition == MDY)
				datePattern = "%B %d %Y";
			else
				datePattern = "%d %B %Y";
		}

		if (options & ArticleBefore)
			datePattern = "le " + datePattern;
	}

	if (timeFormat == HoursMinutes)
	{
		if (_country.in({"AU", "BD", "CA", "CO", "CR", "EG", "SV", "GH", "HN", "HK",
		                "IN", "IR", "IE", "JO", "MY", "MX", "NZ", "NI", "NG", "PK",
		                "PH", "SA", "SG", "UK", "US", "VE"}))
			timePattern = "%I:%M %p";
		else
			timePattern = "%H:%M";
	}
	else if (timeFormat == HoursMinutesSeconds)
		timePattern = "%X";

	if (dateFormat != NoDate && timeFormat != NoTime)
		pattern = datePattern + " à " + timePattern;
	else if (dateFormat != NoDate)
		pattern = datePattern;
	else
		pattern = timePattern;

	return parseDateTime(dateTime, pattern);
}