bool KArchive::writeFile( const QString& name, const QString& user,
						  const QString& group, const char* data, qint64 size,
						  mode_t perm, time_t atime, time_t mtime, time_t ctime )
{
	if ( !prepareWriting( name, user, group, size, perm, atime, mtime, ctime ) )
	{
		qWarning() << "prepareWriting failed";
		return false;
	}

	// Write data
	// Note: if data is 0L, don't call write, it would terminate the KFilterDev
	if ( data && size && !writeData( data, size ) )
	{
		qWarning() << "writeData failed";
		return false;
	}

	if ( !finishWriting( size ) )
	{
		qWarning() << "finishWriting failed";
		return false;
	}
	return true;
}
 VideoWriter_ufmf::~VideoWriter_ufmf() 
 {
     stopBackgroundModeling();
     stopCompressors();
     threadPoolPtr_ -> waitForDone();
     finishWriting();
 } 
void HTMLImportLoader::notifyFinished(Resource* resource)
{
    // The writer instance indicates that a part of the document can be already loaded.
    // We don't take such a case as an error because the partially-loaded document has been visible from script at this point.
    if (resource->loadFailedOrCanceled() && !m_writer) {
        setState(StateError);
        return;
    }

    setState(finishWriting());
}
Exemple #4
0
void MulNode::run(){
  bool inputReady = (!inVar1.empty)&&(!inVar2.empty);
  if(inputReady && outVarEmpty(outVar)){
    for(size_t i=0;i<Node::frameSize;i++){
      outBuffer[i] = in1[i]*in2[i]; 
    }
    finishReading(inVar1);
    finishReading(inVar2);
    finishWriting(outVar);
  }
}
/*******************************************************************************
 * Name of Function:    writerHandler
 * Purpose:             writes the writer output file till maximum item
 * Parameters:          pointer to arguments as void
 * Return Value:        void
 * Calls to:            startWriting, writeData, finishWriting
 * Called from:         main
 * Method:              1. get mutually exclusive access to writer output file
 *                      2. writes 5 items
 *                      3. release the shared writer file
 *                      4. repeats this process till max iteration(20) for each
 *                      writer
 ******************************************************************************/
void *writerHandler (void *args)
{
    struct writer_struct *writer;
    int i;
    
    writer = (struct writer_struct *)args;
    
    /* write till max iterations for each writer */
    for(i=1;i<=MAX_ITERATIONS;i++)
    {
        printf("%ld W%d waiting-for-lock\n", timeElapsed(), writer->w_id);
        startWriting(writer->monitor, writer->w_id);
        printf("%ld W%d lock-acquired\n", timeElapsed(), writer->w_id);
        
        writeData(writer->w_id, &(writer->w_item));
        
        finishWriting(writer->monitor);
        printf("%ld W%d lock-released\n",timeElapsed(), writer->w_id);
    }
    return;
}
void AMContinuousScanActionControllerAMDSClientDataRequestFileWriter::writeToFile(const AMDSClientDataRequestMap &clientDataRequestMap)
{
	QDataStream dataStream(clientDataRequestFile_);

	quint16 numberOfRequests = clientDataRequestMap.count();
	dataStream << numberOfRequests;

	AMDSClientDataRequest *oneClientRequest;
	QMap<QString, AMDSClientDataRequest*>::const_iterator i = clientDataRequestMap.constBegin();
	while(i != clientDataRequestMap.constEnd()){
		oneClientRequest = i.value();
		AMDSClientRequest::encodeAndwriteClientRequest(&dataStream, oneClientRequest);
		i++;
	}

	QMap<QString, AMDSClientDataRequest*>::const_iterator j = clientDataRequestMap.constBegin();
	while(j != clientDataRequestMap.constEnd()){
		j.value()->deleteLater();
		j++;
	}

	finishWriting();
}
Exemple #7
0
void Worker::answer(int fd) {

    assert(clients.find(fd) != clients.end());
    assert(!clients[fd]->outBuf.empty());

    std::string resp = clients[fd]->outBuf;
    printf("[worker #%d]:\t%s", myID, resp.c_str());
    ssize_t sent = send(fd, resp.c_str(), resp.size() + 1, 0);

    if (sent > 0) {

        if (sent == resp.size() + 1) {
            /* Clear outBuf */
            clients[fd]->outBuf.clear();
            /* Remove write event for client */
            finishWriting(fd);

        } else {
            /* Decrease string size */
            clients[fd]->outBuf = clients[fd]->outBuf.substr(sent);
        }
    }
}
Exemple #8
0
bool KArchive::writeFile(const QString &name, const QByteArray &data,
                         mode_t perm,
                         const QString &user, const QString &group, const QDateTime &atime,
                         const QDateTime &mtime, const QDateTime &ctime)
{
    const qint64 size = data.size();
    if (!prepareWriting(name, user, group, size, perm, atime, mtime, ctime)) {
        //qWarning() << "prepareWriting failed";
        return false;
    }

    // Write data
    // Note: if data is null, don't call write, it would terminate the KCompressionDevice
    if (data.constData() && size && !writeData(data.constData(), size)) {
        //qWarning() << "writeData failed";
        return false;
    }

    if (!finishWriting(size)) {
        //qWarning() << "finishWriting failed";
        return false;
    }
    return true;
}
void HTMLImportLoader::notifyFinished(Resource*)
{
    setState(finishWriting());
}
Exemple #10
0
/*
FUNCTION: ReadFromPort
DATE: 11/28/2015
REVISIONS: v4 12/2/2015 - wait state added
DESIGNER: Allen & Dylan & Thomas
PROGRAMMER: Allen & Dylan
INTERFACE: static DWORD WINAPI ReadFromPort(LPVOID lpParam)
			LPVOID lpParam : parameter passed to the thread; intended to be a communications handle
RETURNS: 1

NOTES: This function is intended to be called on a separate thread.
		It has the event driven code to monitor the serial port for INCOMING communications.
		It will send messages to the main window (via WndProc) for OUTGOING communications.
*/
static DWORD WINAPI ReadFromPort(LPVOID lpParam) {
	OVERLAPPED overlapped = { 0 };
	HANDLE hnd = 0;
	BOOL fWaitingOnRead = FALSE;
	overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
	CHAR buffer[PACKETLENGTH] = "";
	DWORD dwEvent;
	SetCommMask(lpParam, EV_RXCHAR);

	while (true) {
		switch (state) {
		// Waiting for ENQ ACKnowledgment
		case WENQACK:
			if (!fWaitingOnRead) {
				if (!WaitCommEvent(lpParam, &dwEvent, &overlapped)) {
					if (GetLastError() == ERROR_IO_PENDING) {
						fWaitingOnRead = TRUE;
					}
				}
			}
			else {
				if (Wait(overlapped.hEvent, TIMEOUT)) {
					if (!ReadFile(lpParam, buffer, 1, NULL, &overlapped)) {
						WaitForSingleObject(overlapped.hEvent, TIMEOUT);
					};

					OutputDebugString("Finished reading in WENQACK\n");
					if (buffer[0] == ACK) {
						SendMessage(hMain, WM_COMMAND, ACK_REC, NULL);
						
					}
					else {
						OutputDebugString("Was not ACK, was ");
						OutputDebugString(buffer);
						OutputDebugString("\n");
						state = WAIT;
					}
					fWaitingOnRead = FALSE;
				}
				else {
					state = IDLE;
				}
			}
			break;
		// Waiting for ACKnowledgment for a packet
		case WACK:
			if (!fWaitingOnRead) {
				if (!WaitCommEvent(lpParam, &dwEvent, &overlapped)) {
					if (GetLastError() == ERROR_IO_PENDING) {
						fWaitingOnRead = TRUE;
					}
				}
			}
			else {
				if (Wait(overlapped.hEvent, TIMEOUT)) {
					ReadFile(lpParam, &buffer, 1, NULL, &overlapped);
					if (buffer[0] == ACK) {
						SendMessage(hMain, WM_COMMAND, ACK_REC, NULL);
						buffer[0] = 0;
					}
					fWaitingOnRead = FALSE;
				}
				else {
					state = WAIT;
				}
			}
			break;
		// a backoff state, can only become a receiver for some time
		case WAIT:
		// default state, can move to sending or receiving
		case IDLE:
			if (!fWaitingOnRead) {
				if ((state == WAIT || state == IDLE) && !WaitCommEvent(lpParam, &dwEvent, &overlapped)) {
					if (GetLastError() == ERROR_IO_PENDING) {
						fWaitingOnRead = TRUE;
					}

				}
			}
			else {
				if ((state == WAIT || state == IDLE) && Wait(overlapped.hEvent, TIMEOUT)) {
					ReadFile(lpParam, &buffer, 1, NULL, &overlapped);
					if (buffer[0] == ENQ) {
						startWriting();
						SendAck(lpParam);
						finishWriting();
						state = RECEIVING;
					}
					// this is what you call a hack to get around race conditions
					else if ((state == WENQACK || state == WACK) && buffer[0] == ACK) {
						SendMessage(hMain, WM_COMMAND, ACK_REC, NULL);
					}
		
					fWaitingOnRead = FALSE;
				}
				else {
					state = IDLE;
				}
			}
			break;
		// anticipating a packet
		case RECEIVING:
			if (!fWaitingOnRead) {
				if (!WaitCommEvent(lpParam, &dwEvent, &overlapped)) {
					if (GetLastError() == ERROR_IO_PENDING) {
						fWaitingOnRead = TRUE;
					}

				}
			}
			else {
				if (Wait(overlapped.hEvent, INFINITE)) {
					receiveBuffer = ReceivePacket(lpParam, overlapped);
					if (ErrorCheck(receiveBuffer) || 1) {
						//DoNonReadingStuff(receiveBuffer);
						Depacketize(receiveBuffer);
						startWriting();
						SendAck(lpParam);
						finishWriting();
						packetsReceived++;
						SetStatistics();
						// open the file for writing and reading

						hnd = CreateFile(FileName, FILE_APPEND_DATA | GENERIC_WRITE | GENERIC_READ, NULL, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
						startWriting();
						if (WritePacketToFile(receiveBuffer, hnd)) {
							UpdateWindowFromFile(hReceive, hnd);
						}
						finishWriting();
						CloseHandle(hnd);

						fWaitingOnRead = FALSE;
						state = IDLE;
						buffer[0] = 0;
						free(receiveBuffer);
					}
				}
				else {
					state = IDLE;
				}
			}
			break;
		}
		// if a packet is in the queue and the process is in idle, attempt to send
		if (state == IDLE && packetBuffer[currentPacket][0] != 0) {
			SendMessage(hMain, WM_COMMAND, ASN_ENQ, NULL);
		}
	}
	return 1;
}
Exemple #11
0
/*
FUNCTION: WndProc
DATE: 12/2/2015
REVISIONS: v3 - changed all IO operations to overlapped
DESIGNER: Dylan & Allen & Thomas
PROGRAMMER: Dylan & Allen
INTERFACE: LRESULT CALLBACK WndProc (HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)
			HWND hwnd : handle to the the main window
			UINT Message : message sent from the message loop to the window
			WPARAM wParam : parameters to the message
			LPARAM lParam : parameters to the message
RETURNS: The default window procedure or 0

NOTES: Handles all button presses from the main window as well as
		events from the serial port reading thread
*/
LRESULT CALLBACK WndProc (HWND hwnd, UINT Message,
                          WPARAM wParam, LPARAM lParam) 
{

	switch (Message)
	{
	case WM_CREATE:
		break;
	case WM_COMMAND:
		switch (LOWORD(wParam)) {
		case ASN_ENQ:
			if (state != IDLE && state != WAIT) {
				OutputDebugString("ENQ but not idling\n");
				break;
			}
			startWriting();
			// send ENQ to the serial port and assume it never fails
			WriteFile(hComm, enq, 1, NULL, &OVERLAPPED());
			state = WENQACK;
			OutputDebugString("ENQ sent\n");
			finishWriting();
			break;
		case ASN_SET:
			startWriting();
			if (!CommConfigDialog(TEXT("com1"), hMain, &cc)) {
				return FALSE;
			}
			else {
				SetCommConfig(hComm, &cc, cc.dwSize);
				PurgeComm(hComm, PURGE_RXCLEAR);
			}
			finishWriting();
			break;
		case ASN_CON:
			OpenFileDialog();
			break;
		case ASN_CLR:
			ClearTextBoxes();
			break;
		case ASN_QUIT:
			PostQuitMessage(0);
			break;
		case ASN_HLP:
			break;
		case ASN_OPN:
			OpenFileDialog();
			break;
		case ACK_REC:
			if (state != WACK && state != WENQACK) {
				OutputDebugString("ACK received but not waiting for ACK before sending a packet\n");
				break;
			}
			if (state == WENQACK) {
				OutputDebugString("ACK received\n");
				acksReceived++;
				SetStatistics();
				if (packetBuffer[currentPacket][0] != 0) {
					OVERLAPPED overlapped = { 0 };
					overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
					startWriting();
					if (!WriteFile(hComm, packetBuffer[currentPacket++], PACKETLENGTH, NULL, &overlapped)) {
						WaitForSingleObject(overlapped.hEvent, TIMEOUT);						
					}

					OutputDebugString("Sent a packet\n");
					packetsSent++;
					SetStatistics();
					// ENQ the line to send the next packet
					// THIS SHOULD BE REPLACED BY THE APPROPRIATE PRIORTIY PROTOCOL
					/*
					if (packetBuffer[currentPacket][0] != 0) {
						WriteFile(hComm, enq, 1, NULL, NULL);
					}
					*/
					finishWriting();
				}
				OutputDebugString("Going to WACK state\n");
				state = WACK;
				break;
			}
			if (state == WACK) {
				OutputDebugString("Packet confirmed received\n");
				OutputDebugString("Going to WAIT state\n");
				state = WAIT;
				packsAcked++;
				acksReceived++;
				SetStatistics();
			}
			break;
		}
		break; // end WM_COMMAND
	case WM_CHAR:
		break;
	case WM_SIZE:
		break;
	case WM_DESTROY:	// Terminate program
		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hwnd, Message, wParam, lParam);
	}
	return 0;
}
Exemple #12
0
bool KArchive::addLocalFile( const QString& fileName, const QString& destName )
{
    QFileInfo fileInfo( fileName );
    if ( !fileInfo.isFile() && !fileInfo.isSymLink() )
    {
        kWarning() << fileName << "doesn't exist or is not a regular file.";
        return false;
    }

    KDE_struct_stat fi;
    if (KDE::lstat(fileName,&fi) == -1) {
        kWarning() << "stat'ing" << fileName
        	<< "failed:" << strerror(errno);
        return false;
    }

    if (fileInfo.isSymLink()) {
        QString symLinkTarget;
        // Do NOT use fileInfo.readLink() for unix symlinks!
        // It returns the -full- path to the target, while we want the target string "as is".
#if defined(Q_OS_UNIX) && !defined(Q_OS_OS2EMX)
        const QByteArray encodedFileName = QFile::encodeName(fileName);
        QByteArray s;
#if defined(PATH_MAX)
        s.resize(PATH_MAX+1);
#else
        int path_max = pathconf(encodedFileName.data(), _PC_PATH_MAX);
        if (path_max <= 0) {
            path_max = 4096;
        }
        s.resize(path_max);
#endif
        int len = readlink(encodedFileName.data(), s.data(), s.size() - 1);
        if ( len >= 0 ) {
            s[len] = '\0';
            symLinkTarget = QFile::decodeName(s);
        }
#endif
        if (symLinkTarget.isEmpty()) // Mac or Windows
            symLinkTarget = fileInfo.symLinkTarget();
        return writeSymLink(destName, symLinkTarget, fileInfo.owner(),
                            fileInfo.group(), fi.st_mode, fi.st_atime, fi.st_mtime,
                            fi.st_ctime);
    }/*end if*/

    qint64 size = fileInfo.size();

    // the file must be opened before prepareWriting is called, otherwise
    // if the opening fails, no content will follow the already written
    // header and the tar file is effectively f*cked up
    QFile file( fileName );
    if ( !file.open( QIODevice::ReadOnly ) )
    {
        kWarning() << "couldn't open file " << fileName;
        return false;
    }

    if ( !prepareWriting( destName, fileInfo.owner(), fileInfo.group(), size,
    		fi.st_mode, fi.st_atime, fi.st_mtime, fi.st_ctime ) )
    {
        kWarning() << " prepareWriting" << destName << "failed";
        return false;
    }

    // Read and write data in chunks to minimize memory usage
    QByteArray array;
    array.resize( int( qMin( qint64( 1024 * 1024 ), size ) ) );
    qint64 n;
    qint64 total = 0;
    while ( ( n = file.read( array.data(), array.size() ) ) > 0 )
    {
        if ( !writeData( array.data(), n ) )
        {
            kWarning() << "writeData failed";
            return false;
        }
        total += n;
    }
    Q_ASSERT( total == size );

    if ( !finishWriting( size ) )
    {
        kWarning() << "finishWriting failed";
        return false;
    }
    return true;
}
bool KArchive::addLocalFile(const QString &fileName, const QString &destName)
{
    QFileInfo fileInfo(fileName);
    if (!fileInfo.isFile() && !fileInfo.isSymLink()) {
        setErrorString(
            tr("%1 doesn't exist or is not a regular file.")
            .arg(fileName));
        return false;
    }

#if defined(Q_OS_UNIX)
#define STAT_METHOD QT_LSTAT
#else
#define STAT_METHOD QT_STAT
#endif
    QT_STATBUF fi;
    if (STAT_METHOD(QFile::encodeName(fileName).constData(), &fi) == -1) {
        setErrorString(
            tr("Failed accessing the file %1 for adding to the archive. The error was: %2")
            .arg(fileName)
            .arg(QLatin1Literal{strerror(errno)}));
        return false;
    }

    if (fileInfo.isSymLink()) {
        QString symLinkTarget;
        // Do NOT use fileInfo.readLink() for unix symlinks!
        // It returns the -full- path to the target, while we want the target string "as is".
#if defined(Q_OS_UNIX) && !defined(Q_OS_OS2EMX)
        const QByteArray encodedFileName = QFile::encodeName(fileName);
        QByteArray s;
#if defined(PATH_MAX)
        s.resize(PATH_MAX + 1);
#else
        int path_max = pathconf(encodedFileName.data(), _PC_PATH_MAX);
        if (path_max <= 0) {
            path_max = 4096;
        }
        s.resize(path_max);
#endif
        int len = readlink(encodedFileName.data(), s.data(), s.size() - 1);
        if (len >= 0) {
            s[len] = '\0';
            symLinkTarget = QFile::decodeName(s.constData());
        }
#endif
        if (symLinkTarget.isEmpty()) { // Mac or Windows
            symLinkTarget = fileInfo.symLinkTarget();
        }
        return writeSymLink(destName, symLinkTarget, fileInfo.owner(),
                            fileInfo.group(), fi.st_mode, fileInfo.lastRead(), fileInfo.lastModified(),
                            fileInfo.created());
    }/*end if*/

    qint64 size = fileInfo.size();

    // the file must be opened before prepareWriting is called, otherwise
    // if the opening fails, no content will follow the already written
    // header and the tar file is effectively f*cked up
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly)) {
        setErrorString(
            tr("Couldn't open file %1: %2")
            .arg(fileName)
            .arg(file.errorString()));
        return false;
    }

    if (!prepareWriting(destName, fileInfo.owner(), fileInfo.group(), size,
                        fi.st_mode, fileInfo.lastRead(), fileInfo.lastModified(), fileInfo.created())) {
        //qCWarning(KArchiveLog) << " prepareWriting" << destName << "failed";
        return false;
    }

    // Read and write data in chunks to minimize memory usage
    QByteArray array;
    array.resize(int(qMin(qint64(1024 * 1024), size)));
    qint64 n;
    qint64 total = 0;
    while ((n = file.read(array.data(), array.size())) > 0) {
        if (!writeData(array.data(), n)) {
            //qCWarning(KArchiveLog) << "writeData failed";
            return false;
        }
        total += n;
    }
    Q_ASSERT(total == size);

    if (!finishWriting(size)) {
        //qCWarning(KArchiveLog) << "finishWriting failed";
        return false;
    }
    return true;
}