/*----------------------------------------------------------------------
|   PLT_SsdpSender::SendSsdp
+---------------------------------------------------------------------*/
NPT_Result
PLT_SsdpSender::SendSsdp(NPT_HttpRequest&   request,
                         const char*        usn,
                         const char*        target,
                         NPT_UdpSocket&     socket,
                         bool               notify,
                         const NPT_SocketAddress* addr /* = NULL */)
{
    NPT_CHECK_SEVERE(FormatPacket(request, usn, target, socket, notify));

    // logging
    NPT_String prefix = NPT_String::Format("Sending SSDP %s packet for %s",
        (const char*)request.GetMethod(), 
        usn);
    PLT_LOG_HTTP_MESSAGE(NPT_LOG_LEVEL_FINER, prefix, &request);

    // use a memory stream to write all the data
    NPT_MemoryStream stream;
    NPT_Result res = request.Emit(stream);
    NPT_CHECK(res);

    // copy stream into a data packet and send it
    NPT_LargeSize size;
    stream.GetSize(size);
    if (size != (NPT_Size)size) NPT_CHECK(NPT_ERROR_OUT_OF_RANGE);

    NPT_DataBuffer packet(stream.GetData(), (NPT_Size)size);
    NPT_CHECK_WARNING(socket.Send(packet, addr));
    return NPT_SUCCESS;
}
Exemple #2
0
/*----------------------------------------------------------------------
|   OZN_Statement::Bind
+---------------------------------------------------------------------*/
NPT_Result 
OZN_Statement::Bind(const OZN_TableDescription& desc,
                    const OZN_Properties&       properties)
{
    NPT_Result    result;
    NPT_Ordinal   bind_index = 1;
    OZN_Property* property;

    // verify input params
    if (properties.GetProperties().GetItemCount() == 0) 
        return NPT_ERROR_INVALID_PARAMETERS;

    // bind now
    for (NPT_Cardinal i=0; i<desc.property_descs_count; i++) {
        property = properties.GetProperty(i);
        if (!property) continue;

        if (i == 0) {
            // bind key, if table is auto assigned, override property type to INTEGER
            result = BindValue(
                bind_index++,
                desc.auto_assign?OZN_PROPERTY_TYPE_INTEGER:desc.property_descs[i].type,
                property->GetValue().string);
            NPT_CHECK(result);
        } else {
            result = Bind(
                bind_index++,
                property);
            NPT_CHECK(result);
        }
    }

    return NPT_SUCCESS;
}
Exemple #3
0
/*----------------------------------------------------------------------
|   NPT_OutputStream::WriteLine
+---------------------------------------------------------------------*/
NPT_Result
NPT_OutputStream::WriteLine(const char* buffer)
{
    NPT_CHECK(WriteString(buffer));
    NPT_CHECK(WriteFully((const void*)"\r\n", 2));

    return NPT_SUCCESS;
}
Exemple #4
0
/*----------------------------------------------------------------------
|       GetEndPointUdpSocket
+---------------------------------------------------------------------*/
static NPT_Result
GetEndPointUdpSocket(EndPoint* endpoint, NPT_UdpSocket*& udp_socket)
{
    // default return values
    udp_socket = NULL;

    switch (endpoint->type) {
      case ENDPOINT_TYPE_UDP_SERVER:
        {
            udp_socket = new NPT_UdpSocket();

            // info
            if (Options.verbose) {
                NPT_Debug("listening on port %d", endpoint->info.udp_server.port);
            }

            // listen on port, any addr
            return udp_socket->Bind(NPT_SocketAddress(NPT_IpAddress::Any, endpoint->info.udp_server.port));
        }
        break;

      case ENDPOINT_TYPE_MULTICAST_SERVER:
        {
            NPT_UdpMulticastSocket* udp_multicast_socket = new NPT_UdpMulticastSocket();
            udp_socket = udp_multicast_socket;

            // info
            if (Options.verbose) {
                NPT_Debug("listening on port %d\n", endpoint->info.multicast_server.port);
            }

            // listen on port, any addr
            NPT_CHECK(udp_socket->Bind(NPT_SocketAddress(NPT_IpAddress::Any, endpoint->info.multicast_server.port)));

            // info
            if (Options.verbose) {
                NPT_Debug("joining multicast group %s\n", endpoint->info.multicast_server.groupname);
            }

            // resolve name
            NPT_IpAddress address;
            NPT_CHECK(address.ResolveName(endpoint->info.multicast_server.groupname));

            // join the group
            NPT_CHECK(udp_multicast_socket->JoinGroup(address));

            return NPT_SUCCESS;
        }
        break;

      default:
          return NPT_FAILURE;
    }

    return NPT_SUCCESS;
}
Exemple #5
0
/*----------------------------------------------------------------------
|   OZN_Database::CheckTableSchema
+---------------------------------------------------------------------*/
NPT_Result 
OZN_Database::CheckTableSchema(const OZN_TableDescription& desc) 
{
    NPT_Result          res = NPT_FAILURE;
    NPT_String          sql;
    NPT_String          sql_create;
    OZN_StringProperty  schema(0, "");
    const char*         result;

    // generate the sql statement we would use to create the table
    NPT_CHECK(OZN_Sql::CreateTable(desc, sql_create));

    // generate the sql statement to query for a table schema
    NPT_CHECK(OZN_Sql::GetTableSchema(desc.name, sql));

    // query the db, if the table doesn't exist it will fail
    res = ExecuteScalar(sql, schema);
    result = schema.GetValue().string;
    if (NPT_SUCCEEDED(res) && result && result[0] != '\0') {
        //if existing table schema sql matches the one we would use
        // then it is the same table and same schema version
        if (NPT_StringsEqual(result, sql_create)) {
            return NPT_SUCCESS;
        }

        // weird, the query succeeded but returned nothing
        return NPT_FAILURE;
    }

    // close bracket
    OZN_Sql::Close(sql_create);

    // table doesn't exist, create it
    NPT_CHECK(ExecuteDML(sql_create, NULL));

    if (desc.unique_index_ids_count && desc.unique_index_ids) {
        res = OZN_Sql::CreateUniqueIndex(desc, 
            desc.unique_index_ids,
            desc.unique_index_ids_count,
            sql);
        NPT_CHECK(res);

        // close bracket
        OZN_Sql::Close(sql);

        // create unique index
        NPT_CHECK(ExecuteDML(sql, NULL));
    }

    return NPT_SUCCESS;
}
Exemple #6
0
/*----------------------------------------------------------------------
|   PLT_HttpClient::WaitForResponse
+---------------------------------------------------------------------*/
NPT_Result
PLT_HttpClient::WaitForResponse(NPT_InputStreamReference& input_stream,
                                NPT_HttpRequest&          request, 
                                NPT_SocketInfo&           info, 
                                NPT_HttpResponse*&        response)
{
    NPT_COMPILER_UNUSED(info);

    // create a buffered stream for this connection stream
    NPT_BufferedInputStreamReference buffered_input_stream(new NPT_BufferedInputStream(input_stream));

    // parse the response
    NPT_CHECK(NPT_HttpResponse::Parse(*buffered_input_stream, response));

    // unbuffer the stream
    buffered_input_stream->SetBufferSize(0);

    // create an entity if one is expected in the response
    if (request.GetMethod() == NPT_HTTP_METHOD_GET || request.GetMethod() == NPT_HTTP_METHOD_POST) {
        NPT_HttpEntity* response_entity = new NPT_HttpEntity(response->GetHeaders());
        // Transfer-Encoding: chunked ?
        if (response_entity->GetTransferEncoding() == "chunked") {
            NPT_InputStreamReference body_stream(new NPT_HttpChunkedDecoderInputStream(buffered_input_stream));
            response_entity->SetInputStream((NPT_InputStreamReference)body_stream);
        } else {
            response_entity->SetInputStream((NPT_InputStreamReference)buffered_input_stream);
        }
        response->SetEntity(response_entity);
    }

    return NPT_SUCCESS;
}
Exemple #7
0
/*----------------------------------------------------------------------
|   NPT_DirectorySplitFilePath
+---------------------------------------------------------------------*/
NPT_Result 
NPT_DirectorySplitFilePath(const char* filepath, 
                           NPT_String& path, 
                           NPT_String& filename)
{
    if (!filepath || filepath[0] == '\0') 
        return NPT_ERROR_INVALID_PARAMETERS;

    path = filepath;

    char       last_char;
    NPT_Int32  i = path.GetLength();
    do {
        last_char = path[i-1];
        if (last_char == '\\' || last_char == '/') 
            break;
    } while (--i);

    // we need at least one delimiter and it cannot be last
    if (i == 0 || i == (NPT_Int32)path.GetLength())  {
        return NPT_ERROR_INVALID_PARAMETERS;
    }

    // assign filename
    filename = filepath+i;

    // truncate path & remove trailing slashes
    NPT_CHECK(path.SetLength(i-1));

    // remove excessive delimiters
    path.TrimRight("/");
    path.TrimRight("\\");
    return NPT_SUCCESS;
}
Exemple #8
0
/*----------------------------------------------------------------------
|       ReadChunk
+---------------------------------------------------------------------*/
static NPT_Result
ReadChunk(NPT_RingBuffer& buffer)
{
    static unsigned int total_read = 0;
    unsigned int chunk = rand()%BUFFER_SIZE;
    unsigned int can_read = buffer.GetAvailable();
    if (chunk > can_read) chunk = can_read;
    if (chunk == 0) return NPT_SUCCESS;

    // read a chunk
    unsigned char bytes[BUFFER_SIZE];
    NPT_CHECK(buffer.Read(bytes, chunk));

    // check values
    for (unsigned int i=0; i<chunk; i++) {
        unsigned int index = total_read+i;
        unsigned char expected = index & 0xFF;
        if (bytes[i] != expected) {
            printf("unexpected byte at index %d (expected %d, got %d)\n",
                   index, expected, bytes[i]);
            return NPT_FAILURE;
        }
    }
    total_read += chunk;

    return NPT_SUCCESS;
}
Exemple #9
0
/*----------------------------------------------------------------------
|    CreateNewFile
+---------------------------------------------------------------------*/
NPT_Result
CreateNewFile(const char* filename, NPT_Size chunk_count, NPT_Size chunk_size=1)
{
    NPT_File file(filename);
    NPT_CHECK(file.Open(NPT_FILE_OPEN_MODE_CREATE|NPT_FILE_OPEN_MODE_WRITE));
    NPT_OutputStreamReference out;
    file.GetOutputStream(out);
    unsigned char* chunk_buffer = new unsigned char[chunk_size];
    for (unsigned int i=0; i<chunk_size; i++) {
        chunk_buffer[i] = (unsigned char)i;
    }
    for (unsigned int i=0; i<chunk_count; i++) {
        NPT_ASSERT(NPT_SUCCEEDED(out->WriteFully(chunk_buffer, chunk_size)));
    }
    delete[] chunk_buffer;
    file.Close();
    out = NULL;

    NPT_FileInfo info;
    NPT_Result result = NPT_File::GetInfo(filename, &info);
    NPT_ASSERT(NPT_SUCCEEDED(result));
    NPT_ASSERT(info.m_Size == (NPT_LargeSize)chunk_count*(NPT_LargeSize)chunk_size);

    return NPT_SUCCESS;
}
Exemple #10
0
/*----------------------------------------------------------------------
|   OZN_Database::Create
+---------------------------------------------------------------------*/
NPT_Result 
OZN_Database::Create(const char*    path, 
                     NPT_Int32      busy_timeout_ms, 
                     bool           create_file,
                     OZN_Database*& db)
{
    int         result;
    sqlite3*    m_Sq3Db;

    // reset output params
    db = NULL;

    if (create_file) {
        NPT_FileInfo info;
        result = NPT_File::GetInfo(path, &info);
        if (NPT_FAILED(result)) {
            NPT_File file(path);
            NPT_CHECK(file.Open(NPT_FILE_OPEN_MODE_CREATE | NPT_FILE_OPEN_MODE_WRITE | NPT_FILE_OPEN_MODE_TRUNCATE));
            file.Close();

            // try to get type again
            NPT_CHECK(NPT_File::GetInfo(path, &info));
        }

        // check that this is a file 
        if (info.m_Type != NPT_FileInfo::FILE_TYPE_REGULAR) {
            NPT_Debug("The path %s does not point to a file, please check the path", path);
            return OZN_ERROR_DB_INVALID_FILEPATH;
        }        
    }

    result = sqlite3_open(path, &m_Sq3Db);
    if (result != SQLITE_OK) {
        //const char* errmsg = sqlite3_errmsg(m_Sq3Db);
        return OZN_MapErrorCode(result);
    }

    // create db now
    db = new OZN_Database(m_Sq3Db, busy_timeout_ms);

    // sets a custom busy handler
    sqlite3_busy_handler(m_Sq3Db, OZN_BusyHandler, db);

    return NPT_SUCCESS;
}
Exemple #11
0
/*----------------------------------------------------------------------
|   NPT_InputStream::Skip
+---------------------------------------------------------------------*/
NPT_Result
NPT_InputStream::Skip(NPT_Size count)
{
    // get the current location
    NPT_Position position;
    NPT_CHECK(Tell(position));

    // seek ahead
    return Seek(position+count);
}
Exemple #12
0
/*----------------------------------------------------------------------
|       NPT_PosixQueue::Push
+---------------------------------------------------------------------*/
NPT_Result
NPT_PosixQueue::Push(NPT_QueueItem* item, NPT_Timeout timeout)
{
    struct timespec timed;
    if (timeout != NPT_TIMEOUT_INFINITE) {
        NPT_CHECK(GetTimeOut(timeout, timed));
    }

    // lock the mutex that protects the list
    if (pthread_mutex_lock(&m_Mutex)) {
        return NPT_FAILURE;
    }

    NPT_Result result = NPT_SUCCESS;
    // check that we have not exceeded the max
    if (m_MaxItems) {
        while (m_Items.GetItemCount() >= m_MaxItems) {
            // wait until we can push
            ++m_PushersWaitingCount;
            if (timeout == NPT_TIMEOUT_INFINITE) {
                pthread_cond_wait(&m_CanPushCondition, &m_Mutex);
                --m_PushersWaitingCount;
            } else {
                int wait_res = pthread_cond_timedwait(&m_CanPushCondition, 
                                                      &m_Mutex, 
                                                      &timed);
                --m_PushersWaitingCount;
                if (wait_res == ETIMEDOUT) {
                    result = NPT_ERROR_TIMEOUT;
                    break;
                }
            }

            if (m_Aborting) {
                result = NPT_ERROR_INTERRUPTED;
                break;
            }
        }
    }

    // add the item to the list
    if (result == NPT_SUCCESS) {
        m_Items.Add(item);

        // wake up any thread that may be waiting to pop
        if (m_PoppersWaitingCount) { 
            pthread_cond_broadcast(&m_CanPopCondition);
        }
    }

    // unlock the mutex
    pthread_mutex_unlock(&m_Mutex);

    return result;
}
/*----------------------------------------------------------------------
|   NPT_Win32Queue::Peek
+---------------------------------------------------------------------*/
NPT_Result
NPT_Win32Queue::Peek(NPT_QueueItem*& item, NPT_Timeout timeout)
{
    // default value
    item = NULL;

    // lock the mutex that protects the list
    NPT_CHECK(m_Mutex.Lock());

    NPT_Result result = NPT_SUCCESS;
    NPT_List<NPT_QueueItem*>::Iterator head = m_Items.GetFirstItem();
    if (timeout) {
        while (!head) {
            // no item in the list, wait for one

            // reset the condition to indicate that the queue is empty
            m_CanPopCondition->Reset();

            // unlock the mutex so that another thread can push
            m_Mutex.Unlock();

            // wait for the condition to signal that we can pop
            NPT_Result result = m_CanPopCondition->Wait(timeout);
            if (NPT_FAILED(result)) return result;

            // relock the mutex so that we can check the list again
            NPT_CHECK(m_Mutex.Lock());

            // try again
            head = m_Items.GetFirstItem();
        }
    } else {
        if (!head) result = NPT_ERROR_LIST_EMPTY;
    }

    if (head) item = *head;

    // unlock the mutex
    m_Mutex.Unlock();

    return result;
}
Exemple #14
0
/*----------------------------------------------------------------------
|   NPT_Zip::Deflate
+---------------------------------------------------------------------*/
NPT_Result
NPT_Zip::Deflate(NPT_File& in,
                 NPT_File& out,
                 int       compression_level,
                 Format    format /* = ZLIB */)
{
    // check parameters
    if (compression_level < NPT_ZIP_COMPRESSION_LEVEL_DEFAULT ||
            compression_level > NPT_ZIP_COMPRESSION_LEVEL_MAX) {
        return NPT_ERROR_INVALID_PARAMETERS;
    }

    NPT_InputStreamReference input;
    NPT_CHECK(in.GetInputStream(input));
    NPT_OutputStreamReference output;
    NPT_CHECK(out.GetOutputStream(output));

    NPT_ZipDeflatingInputStream deflating_stream(input, compression_level, format);
    return NPT_StreamToStreamCopy(deflating_stream, *output.AsPointer());
}
/*----------------------------------------------------------------------
|   NPT_Win32Directory::GetInfo
+---------------------------------------------------------------------*/
NPT_Result
NPT_PosixDirectory::GetInfo(NPT_DirectoryInfo& info)
{
    if (!m_Validated) {
        NPT_CHECK(NPT_Directory::GetEntryCount(m_Path, m_Count));
        m_Validated = true;
    }

    info.entry_count = m_Count;
    return NPT_SUCCESS;
}
/*----------------------------------------------------------------------
|   NPT_Win32Queue::Pop
+---------------------------------------------------------------------*/
NPT_Result
NPT_Win32Queue::Pop(NPT_QueueItem*& item, NPT_Timeout timeout)
{
    // default value
    item = NULL;

    // lock the mutex that protects the list
    NPT_CHECK(m_Mutex.Lock());

    NPT_Result result;
    if (timeout) {
        while ((result = m_Items.PopHead(item)) == NPT_ERROR_LIST_EMPTY) {
            // no item in the list, wait for one

            // reset the condition to indicate that the queue is empty
            m_CanPopCondition->Reset();

            // unlock the mutex so that another thread can push
            m_Mutex.Unlock();

            // wait for the condition to signal that we can pop
            NPT_Result result = m_CanPopCondition->Wait(timeout);
            if (NPT_FAILED(result)) return result;

            // relock the mutex so that we can check the list again
            NPT_CHECK(m_Mutex.Lock());
        }
    } else {
        result = m_Items.PopHead(item);
    }

    if (m_MaxItems && (result == NPT_SUCCESS)) {
        // wake up the threads waiting to push
        m_CanPushCondition->Signal();
    }

    // unlock the mutex
    m_Mutex.Unlock();

    return result;
}
Exemple #17
0
/*----------------------------------------------------------------------
|   NPT_MemoryStream::SetSize
+---------------------------------------------------------------------*/
NPT_Result
NPT_MemoryStream::SetSize(NPT_Size size)
{
    // try to resize the data buffer
    NPT_CHECK(m_Buffer.SetDataSize(size));

    // adjust the read and write offsets
    if (m_ReadOffset > size) m_ReadOffset = size;
    if (m_WriteOffset > size) m_WriteOffset = size;

    return NPT_SUCCESS;
}
/*----------------------------------------------------------------------
|   PLT_PersonRoles::ToDidl
+---------------------------------------------------------------------*/
NPT_Result
PLT_PersonRoles::FromDidl(const NPT_Array<NPT_XmlElementNode*>& nodes)
{
    for (NPT_Cardinal i=0; i<nodes.GetItemCount(); i++) {
        PLT_PersonRole person;
        const NPT_String* name = nodes[i]->GetText();
        const NPT_String* role = nodes[i]->GetAttribute("role");
        if (name) person.name = *name;
        if (role) person.role = *role;
        NPT_CHECK(NPT_List<PLT_PersonRole>::Add(person));
    }
    return NPT_SUCCESS;
}
Exemple #19
0
/*----------------------------------------------------------------------
|   PLT_Artworks::ToDidl
+---------------------------------------------------------------------*/
NPT_Result
PLT_Artworks::FromDidl(const NPT_Array<NPT_XmlElementNode*>& nodes)
{
    for (NPT_Cardinal i=0; i<nodes.GetItemCount(); i++) {
        PLT_Artwork artwork;
        const NPT_String* url = nodes[i]->GetText();
        const NPT_String* type = nodes[i]->GetAttribute("type");
        if (type) artwork.type = *type;
        if (url) artwork.url = *url;
        NPT_CHECK(NPT_List<PLT_Artwork>::Add(artwork));
    }
    return NPT_SUCCESS;
}
Exemple #20
0
/*----------------------------------------------------------------------
|       NPT_PosixQueue::Peek
+---------------------------------------------------------------------*/
NPT_Result
NPT_PosixQueue::Peek(NPT_QueueItem*& item, NPT_Timeout timeout)
{
    struct timespec timed;
    if (timeout != NPT_TIMEOUT_INFINITE) {
        NPT_CHECK(GetTimeOut(timeout, timed));
    }

    // lock the mutex that protects the list
    if (pthread_mutex_lock(&m_Mutex)) {
        return NPT_FAILURE;
    }

    NPT_Result result = NPT_SUCCESS;
    NPT_List<NPT_QueueItem*>::Iterator head = m_Items.GetFirstItem();
    if (timeout) {
        while (!head) {
            // no item in the list, wait for one
            ++m_PoppersWaitingCount;
            if (timeout == NPT_TIMEOUT_INFINITE) {
                pthread_cond_wait(&m_CanPopCondition, &m_Mutex);
                --m_PoppersWaitingCount;
            } else {
                int wait_res = pthread_cond_timedwait(&m_CanPopCondition, 
                                                      &m_Mutex, 
                                                      &timed);
                --m_PoppersWaitingCount;
                if (wait_res == ETIMEDOUT) {
                    result = NPT_ERROR_TIMEOUT;
                    break;
                }
            }

            if (m_Aborting) {
                result = NPT_ERROR_INTERRUPTED;
                break;
            }

            head = m_Items.GetFirstItem();
        }
    } else {
        if (!head) result = NPT_ERROR_LIST_EMPTY;
    }

    item = head?*head:NULL;

    // unlock the mutex
    pthread_mutex_unlock(&m_Mutex);

    return result;
}
Exemple #21
0
/*----------------------------------------------------------------------
|       NPT_PosixQueue::Pop
+---------------------------------------------------------------------*/
NPT_Result
NPT_PosixQueue::Pop(NPT_QueueItem*& item, NPT_Timeout timeout)
{
    struct timespec timed;
    if (timeout != NPT_TIMEOUT_INFINITE) {
        NPT_CHECK(GetTimeOut(timeout, timed));
    }

    // lock the mutex that protects the list
    if (pthread_mutex_lock(&m_Mutex)) {
        return NPT_FAILURE;
    }

    NPT_Result result;
    if (timeout) {
        while ((result = m_Items.PopHead(item)) == NPT_ERROR_LIST_EMPTY) {
            // no item in the list, wait for one
            ++m_PoppersWaitingCount;
            if (timeout == NPT_TIMEOUT_INFINITE) {
                pthread_cond_wait(&m_CanPopCondition, &m_Mutex);
                --m_PoppersWaitingCount;
            } else {
                int wait_res = pthread_cond_timedwait(&m_CanPopCondition, 
                                                      &m_Mutex, 
                                                      &timed);
                --m_PoppersWaitingCount;
                if (wait_res == ETIMEDOUT) {
                    result = NPT_ERROR_TIMEOUT;
                    break;
                }
            }
            
            if (m_Aborting) {
                result = NPT_ERROR_INTERRUPTED;
                break;
            }
        }
    } else {
        result = m_Items.PopHead(item);
    }
    
    // wake up any thread that my be waiting to push
    if (m_MaxItems && (result == NPT_SUCCESS) && m_PushersWaitingCount) {
        pthread_cond_broadcast(&m_CanPushCondition);
    }

    // unlock the mutex
    pthread_mutex_unlock(&m_Mutex);
 
    return result;
}
/*----------------------------------------------------------------------
|   NPT_LogManager::SetConfigValue
+---------------------------------------------------------------------*/
NPT_Result
NPT_LogManager::SetConfigValue(const char* key, const char* value)
{
    NPT_String* value_string = GetConfigValue(key, NULL);
    if (value_string) {
        /* the key already exists, replace the value */
        *value_string = value;
    } else {
        /* the value does not already exist, create a new one */
        NPT_CHECK(LogManager.m_Config.Add(NPT_LogConfigEntry(key, value)));
    }

    return NPT_SUCCESS;
}
Exemple #23
0
NPT_Result
NPT_StreamToStreamCopy(NPT_InputStream&  from,
                       NPT_OutputStream& to,
                       NPT_Position      offset /* = 0 */,
                       NPT_Size          size   /* = 0, 0 means the entire stream */)
{
    // seek into the input if required
    if (offset) {
        NPT_CHECK(from.Seek(offset));
    }

    // allocate a buffer for the transfer
    NPT_Size bytes_transfered = 0;
    NPT_Byte* buffer = new NPT_Byte[NPT_STREAM_COPY_BUFFER_SIZE];
    NPT_Result result = NPT_SUCCESS;
    if (buffer == NULL) return NPT_ERROR_OUT_OF_MEMORY;

    // copy until an error occurs or the end of stream is reached
    for (;;) {
        // read some data
        NPT_Size   bytes_to_read = NPT_STREAM_COPY_BUFFER_SIZE;
        NPT_Size   bytes_read = 0;
        if (size) {
            // a max size was specified
            if (bytes_to_read > size-bytes_transfered) {
                bytes_to_read = size-bytes_transfered;
            }
        }
        result = from.Read(buffer, bytes_to_read, &bytes_read);
        if (NPT_FAILED(result)) {
            if (result == NPT_ERROR_EOS) result = NPT_SUCCESS;
            break;
        }
        if (bytes_read == 0) continue;

        // write the data
        result = to.WriteFully(buffer, bytes_read);
        if (NPT_FAILED(result)) break;

        // update the counts
        if (size) {
            bytes_transfered += bytes_read;
            if (bytes_transfered >= size) break;
        }
    }

    // free the buffer and return
    delete[] buffer;
    return result;
}
/*----------------------------------------------------------------------
|   NPT_Win32Queue::Push
+---------------------------------------------------------------------*/
NPT_Result
NPT_Win32Queue::Push(NPT_QueueItem* item, NPT_Timeout timeout)
{
    // lock the mutex that protects the list
    NPT_CHECK(m_Mutex.Lock());

    // check that we have not exceeded the max
    if (m_MaxItems) {
        while (m_Items.GetItemCount() >= m_MaxItems) {
            // we must wait until some items have been removed

            // reset the condition to indicate that the queue is full
            m_CanPushCondition->Reset();

            // unlock the mutex so that another thread can pop
            m_Mutex.Unlock();

            // wait for the condition to signal that we can push
            NPT_Result result = m_CanPushCondition->Wait(timeout);
            if (NPT_FAILED(result)) return result;

            // relock the mutex so that we can check the list again
            NPT_CHECK(m_Mutex.Lock());
        }
    }

    // add the item to the list
    m_Items.Add(item);

    // wake up the threads waiting to pop
    m_CanPopCondition->Signal();

    // unlock the mutex
    m_Mutex.Unlock();

    return NPT_SUCCESS;
}
Exemple #25
0
/*----------------------------------------------------------------------
|   OZN_Statement::BindValue
+---------------------------------------------------------------------*/
NPT_Result 
OZN_Statement::BindValue(NPT_Ordinal      index,
                         OZN_PropertyType type,
                         const char*      value)
{
    int result;

    if (!value) {
        return Bind(index, NULL);
    }

    switch(type) {
        case OZN_PROPERTY_TYPE_INTEGER: {
            NPT_Int32 data;
            NPT_CHECK(NPT_ParseInteger32(value, data, false));
            result = sqlite3_bind_int((*m_Vm)(), 
                index, 
                data);
            break;
        }        
        
        case OZN_PROPERTY_TYPE_STRING: {
            result = sqlite3_bind_text((*m_Vm)(), 
                index, 
                value, 
                -1, 
                SQLITE_TRANSIENT);
            break;
        }

        case OZN_PROPERTY_TYPE_RAW: {
            result = sqlite3_bind_blob((*m_Vm)(), 
                index,
                (const void*)value, 
                NPT_StringLength(value), 
                SQLITE_TRANSIENT);
            break;
        }

        default:
            return NPT_FAILURE;
    }

    if (result != SQLITE_OK) {
        const char* errmsg = sqlite3_errmsg(m_Db->m_Sq3Db);
    }

    return OZN_MapErrorCode(result);
}
/*----------------------------------------------------------------------
|   NPT_DataBuffer::SetData
+---------------------------------------------------------------------*/
NPT_Result
NPT_DataBuffer::SetData(const NPT_Byte* data, NPT_Size size)
{
    if (size > m_BufferSize) {
        if (m_BufferIsLocal) {
            NPT_CHECK(ReallocateBuffer(size));
        } else {
            return NPT_ERROR_INVALID_STATE;
        }
    }
    if (data) NPT_CopyMemory(m_Buffer, data, size);
    m_DataSize = size;

    return NPT_SUCCESS;
}
/*----------------------------------------------------------------------
|   NPT_DataBuffer::SetDataSize
+---------------------------------------------------------------------*/
NPT_Result
NPT_DataBuffer::SetDataSize(NPT_Size size)
{
    if (size > m_BufferSize) {
        // the buffer is too small, we need to reallocate it
        if (m_BufferIsLocal) {
            NPT_CHECK(ReallocateBuffer(size));
        } else { 
            // we cannot reallocate an external buffer
            return NPT_ERROR_NOT_SUPPORTED;
        }
    }
    m_DataSize = size;
    return NPT_SUCCESS;
}
Exemple #28
0
/*----------------------------------------------------------------------
|   NPT_MemoryStream::Write
+---------------------------------------------------------------------*/
NPT_Result
NPT_MemoryStream::Write(const void* data,
                        NPT_Size    bytes_to_write,
                        NPT_Size*   bytes_written)
{
    NPT_CHECK(m_Buffer.Reserve(m_WriteOffset+bytes_to_write));

    NPT_CopyMemory(m_Buffer.UseData()+m_WriteOffset, data, bytes_to_write);
    m_WriteOffset += bytes_to_write;
    if (m_WriteOffset > m_Buffer.GetDataSize()) {
        m_Buffer.SetDataSize(m_WriteOffset);
    }
    if (bytes_written) *bytes_written = bytes_to_write;

    return NPT_SUCCESS;
}
Exemple #29
0
/*----------------------------------------------------------------------
|   OZN_Database::ExecuteScalar
+---------------------------------------------------------------------*/
NPT_Result 
OZN_Database::ExecuteScalar(const char* sql, OZN_Property& property)
{
    NPT_Result result = NPT_FAILURE;
    OZN_Query* query;

    NPT_CHECK(OZN_Query::Create(this, sql, query));

    if (sqlite3_column_count((*query->m_Vm)()) < 1) goto failure;

    result = query->GetProperty(0, property);

failure:
    delete query;
    return result;
}
/*----------------------------------------------------------------------
|   NPT_LogFileHandler::Open
+---------------------------------------------------------------------*/
NPT_Result
NPT_LogFileHandler::Open(bool append /* = true */)
{
    /* reset stream just in case */
    m_Stream = NULL;
            
    /* open the log file */
    NPT_File file(m_Filename);
    NPT_Result result = file.Open(NPT_FILE_OPEN_MODE_CREATE |
                                  NPT_FILE_OPEN_MODE_READ   |
                                  NPT_FILE_OPEN_MODE_WRITE  |
                                  (append?NPT_FILE_OPEN_MODE_APPEND:NPT_FILE_OPEN_MODE_TRUNCATE));
    if (NPT_FAILED(result)) return result;

    NPT_CHECK(file.GetOutputStream(m_Stream));
    return NPT_SUCCESS;
}