property.cpp 2.5 KB
/***************************************************************************
 *   Universidade Federal da Paraíba                                       *
 *   Copyright (C) 2013 by Laboratório de Aplicações de Vídeo Digital      *
 *                                                                         *
 *   Centro de Informática - UFPB - Campus I                               *
 *   João Pessoa - PB - Brasil                                             *
 *                                                                         *
 *   Author: Leonardo de Araújo Domingues (leonardo.araujo@lavid.ufpb.br)  *
 *   Date: Qui Nov 28 14:06:10 BRT 2013                                    *
 *                                                                         *
 **************************************************************************/

 #include "property.h"


 namespace util {

 	
 	PropertyHandler::PropertyHandler(std::string filename) {
 		try {
 			if (checkFileExtension(filename) != 1)
 				throw new RuntimeException("Format file not is recognized!");
 			file_property = new FileIO(filename, FileIO::MODE_READ);
 		} catch (lavidlib::IOException &ex) { 			
 			printf("[FAILED] Cannot open file %s.\n%s\n", filename.c_str(),
 				ex.getMessage().c_str());
 		}
 	}

 	
 	PropertyHandler::~PropertyHandler() {
 		if (rbuffer)
 			delete rbuffer;
 		if (file_property) 
 			delete file_property;
 	}


 	std::string PropertyHandler::getAttributeValue(std::string attr) {

 		rbuffer = new BufferedReader(file_property);
 		std::string fline;
 		try {
 			int target_pos = -1, begin = 0;
 			std::string attr_t, value_t;

	 		while((fline = rbuffer->readLine()).size() > 0) {	 			
	 			target_pos = fline.find("=");
	 			if (target_pos < 2)
	 				throw new RuntimeException("The assignment symbol was not found.");
	 			
	 			attr_t = fline.substr(begin, target_pos);
	 			begin = target_pos+1;
	 			value_t = fline.substr(begin, fline.size());
	 			if (attr.compare(attr_t) == 0) {
	 				file_property->seek(0);
	 				return value_t;	 				
	 			}
	 			target_pos = -1;
	 			begin = 0;
	 		}
 		} catch (lavidlib::EOFException &ex) {
 			printf("[INFO] File is completed.\n%s\n", ex.getMessage().c_str());
 		}
 		file_property->seek(0);
 		//FIXME: throw new exception
 		return fline;
 	}

 	#define EXTENSION ".conf"

 	int PropertyHandler::checkFileExtension(std::string &filename) {
 		
 		return (filename.find(EXTENSION) > 0 && 
 			(filename.size() == (filename.find(EXTENSION) + strlen(EXTENSION)))) ? 1 : -1; 		

 	}


 }