bool 
TeSQLite::generateLabelPositions(TeTheme *theme, const std::string& objectId)
{
	string	geomTable, upd;
	string	collTable = theme->collectionTable();
	
	if((collTable.empty()) || (!tableExist(collTable)))
		return false;

	if( theme->layer()->hasGeometry(TeCELLS)  )
	{
		geomTable = theme->layer()->tableName(TeCELLS);
		
		upd= "UPDATE " + collTable + " SET ";
		upd += " label_x = (SELECT MAX(lower_x + (upper_x - lower_x)/2) ";
		upd += "FROM " + geomTable + " WHERE object_id = c_object_id), ";
		
		upd += " label_y = (SELECT MAX(lower_y + (upper_y - lower_y)/2) ";
		upd += "FROM " + geomTable + " WHERE object_id = c_object_id) ";
		upd += " WHERE label_x IS NULL OR label_y IS NULL";
	}

	if( theme->layer()->hasGeometry(TePOLYGONS) )
	{
		geomTable = theme->layer()->tableName(TePOLYGONS);
		
		upd= "UPDATE " + collTable + " SET ";
		upd += " label_x = (SELECT MAX(lower_x + (upper_x - lower_x)/2) ";
		upd += "FROM " + geomTable + " WHERE object_id = c_object_id), ";
		
		upd += " label_y = (SELECT MAX(lower_y + (upper_y - lower_y)/2) ";
		upd += "FROM " + geomTable + " WHERE object_id = c_object_id) ";
		upd += " WHERE label_x IS NULL OR label_y IS NULL";
	}
	
	if( theme->layer()->hasGeometry(TeLINES) )
	{
		geomTable = theme->layer()->tableName(TeLINES);

		upd= "UPDATE " + collTable + " SET ";
		upd += " label_x = (SELECT MAX(lower_x + (upper_x - lower_x)/2) ";
		upd += "FROM " + geomTable + " WHERE object_id = c_object_id), ";
		
		upd += " label_y = (SELECT MAX(lower_y + (upper_y - lower_y)/2) ";
		upd += "FROM " + geomTable + " WHERE object_id = c_object_id) ";
		upd += " WHERE label_x IS NULL OR label_y IS NULL";
	}
	
	if(theme->layer()->hasGeometry(TePOINTS))
	{
		geomTable = theme->layer()->tableName(TePOINTS);
		
		upd= " UPDATE " + collTable + " SET ";
		upd += " label_x = (SELECT MAX(x) ";
		upd += " FROM " + geomTable + " p WHERE object_id = c_object_id), ";
		
		upd += " label_y = (SELECT MAX(y) ";
		upd += " FROM " + geomTable + " p WHERE object_id = c_object_id) ";
		upd += " WHERE label_x IS NULL OR label_y IS NULL";
	}

	if (!upd.empty())
	{
		if (!objectId.empty())
		{
			upd += " AND c_object_id='"+objectId+"'";
		}
		if(!execute(upd))
			return false;
	}
	return true;
}
Example #2
0
 bool ParseDouble(const std::string& string, double& value)
 {
   return swri_string_util::ToDouble(string, value) || string.empty();
 }
Example #3
0
 bool ParseUInt32(const std::string& string, uint32_t& value, int32_t base)
 {
   return swri_string_util::ToUInt32(string, value, base) || string.empty();
 }
Example #4
0
bool Parser::parseLine(std::string &ErrStr) {
    switch (CurTok.K) {
    case Token::Ident:
        if (CurTok.str() == "cand") {
            if (RK == ReplacementKind::ParseLHS) {
                ErrStr = makeErrStr("Not expecting 'cand' when parsing LHS");
                return false;
            }
            if (RK == ReplacementKind::ParseRHS) {
                ErrStr = makeErrStr("Not expecting 'cand' when parsing RHS");
                return false;
            }
            if (!consumeToken(ErrStr)) return false;
            InstMapping Cand = parseInstMapping(ErrStr);
            if (!ErrStr.empty()) return false;

            Reps.push_back(ParsedReplacement{Cand, std::move(PCs),
                                             std::move(BPCs)});
            nextReplacement();

            return true;
        } else if (CurTok.str() == "infer") {
            if (RK == ReplacementKind::ParseRHS) {
                ErrStr = makeErrStr("Not expecting 'infer' when parsing RHS");
                return false;
            }
            if (!consumeToken(ErrStr)) return false;
            if (LHS) {
                ErrStr = makeErrStr("Not expecting a second 'infer'");
                return false;
            }
            LHS = parseInst(ErrStr);
            if (!LHS)
                return false;

            if (RK == ReplacementKind::ParseLHS) {
                Reps.push_back(ParsedReplacement{InstMapping(LHS, 0),
                                                 std::move(PCs), std::move(BPCs)});
                nextReplacement();
            }

            return true;
        } else if (CurTok.str() == "result") {
            if (RK == ReplacementKind::ParseLHS) {
                ErrStr = makeErrStr("Not expecting 'result' when parsing LHS");
                return false;
            }
            if (RK != ReplacementKind::ParseRHS && !LHS) {
                ErrStr = makeErrStr("Not expecting 'result' before 'infer'");
                return false;
            }
            if (!consumeToken(ErrStr)) return false;
            Inst *RHS = parseInst(ErrStr);
            if (!RHS)
                return false;
            InstMapping Cand = InstMapping(LHS, RHS);

            Reps.push_back(ParsedReplacement{Cand, std::move(PCs),
                                             std::move(BPCs)});
            nextReplacement();

            return true;
        } else if (CurTok.str() == "pc") {
            if (!consumeToken(ErrStr)) return false;
            InstMapping PC = parseInstMapping(ErrStr);
            if (!ErrStr.empty()) return false;

            PCs.push_back(PC);

            return true;
        } else if (CurTok.str() == "blockpc") {
            if (!consumeToken(ErrStr)) return false;
            if (CurTok.K != Token::ValName) {
                ErrStr = makeErrStr("expected block var");
                return false;
            }
            StringRef InstName = CurTok.Name;
            unsigned InstWidth = CurTok.Width;
            if (InstWidth != 0) {
                ErrStr = makeErrStr("blocks may not have a width");
                return false;
            }
            if (Context.getInst(CurTok.Name)) {
                ErrStr = makeErrStr(std::string("%") + InstName.str() +
                                    " is declared as an inst");
                return false;
            }
            Block *B = Context.getBlock(InstName);
            if (B == 0) {
                ErrStr = makeErrStr(std::string("block %") + InstName.str() +
                                    " is undeclared");
                return false;
            }
            if (!consumeToken(ErrStr)) return false;

            if (CurTok.K != Token::UntypedInt) {
                ErrStr = makeErrStr(std::string("expected block number"));
                return false;
            }
            unsigned CurrIdx = CurTok.Val.getLimitedValue();
            if (!consumeToken(ErrStr)) return false;

            InstMapping PC = parseInstMapping(ErrStr);
            if (!ErrStr.empty()) return false;

            std::map<Block *, unsigned>::iterator IdxIt = BlockPCIdxMap.find(B);
            if (IdxIt == BlockPCIdxMap.end()) {
                BlockPCIdxMap[B] = CurrIdx;
            }
            else {
                assert(BPCs.size() && "Empty BlockPCs!");
                if (CurrIdx > IdxIt->second)
                    BlockPCIdxMap[B] = CurrIdx;
            }
            BPCs.emplace_back(B, CurrIdx, PC);

            return true;
        } else {
            ErrStr = makeErrStr(std::string("unexpected identifier: '") +
                                CurTok.str().str() + "'");
            return false;
        }

    case Token::ValName: {
        StringRef InstName = CurTok.Name;
        unsigned InstWidth = CurTok.Width;

        if (Context.getInst(InstName)) {
            ErrStr = makeErrStr(std::string("%") + InstName.str() +
                                " already declared as an inst");
            return false;
        }
        if (Context.getBlock(InstName)) {
            ErrStr = makeErrStr(std::string("%") + InstName.str() +
                                " already declared as a block");
            return false;
        }

        TokenPos TP = L.getTokenPos(CurTok);
        if (!consumeToken(ErrStr)) return false;

        if (CurTok.K != Token::Eq) {
            ErrStr = makeErrStr("expected '='");
            return false;
        }
        if (!consumeToken(ErrStr)) return false;

        if (CurTok.K != Token::Ident) {
            ErrStr = makeErrStr("expected identifier");
            return false;
        }

        Inst::Kind IK = Inst::getKind(CurTok.str());

        if (IK == Inst::BSwap) {
            if (InstWidth != 16 && InstWidth != 32 && InstWidth != 64) {
                ErrStr = makeErrStr(TP, CurTok.str().str() + " doesn't support " +
                                    std::to_string(InstWidth) + " bits");
                return false;
            }
        }
        if ((IK == Inst::CtPop) || (IK == Inst::Ctlz) || (IK == Inst::Cttz)) {
            if (InstWidth !=8 && InstWidth != 16 && InstWidth != 32 &&
                    InstWidth != 64 && InstWidth != 256) {
                ErrStr = makeErrStr(TP, CurTok.str().str() + " doesn't support " +
                                    std::to_string(InstWidth) + " bits");
                return false;
            }
        }
        if (IK == Inst::Kind(~0)) {
            if (CurTok.str() == "block") {
                if (InstWidth != 0) {
                    ErrStr = makeErrStr(TP, "blocks may not have a width");
                    return false;
                }

                if (!consumeToken(ErrStr))
                    return false;
                if (CurTok.K != Token::UntypedInt) {
                    ErrStr = makeErrStr(TP, "block must be followed by number of preds");
                    return false;
                }
                unsigned Preds = CurTok.Val.getLimitedValue();

                Context.setBlock(InstName, IC.createBlock(Preds));
                return consumeToken(ErrStr);
            } else {
                ErrStr = makeErrStr(std::string("unexpected inst kind: '") +
                                    CurTok.str().str() + "'");
                return false;
            }
        }

        if (IK == Inst::Var && InstWidth == 0) {
            ErrStr = makeErrStr(TP, "var must have a width");
            return false;
        }

        if (!consumeToken(ErrStr)) return false;

        Block *B = 0;

        if (IK == Inst::Var) {
            llvm::APInt Zero(InstWidth, 0, false), One(InstWidth, 0, false),
                 ConstOne(InstWidth, 1, false);
            bool NonZero = false, NonNegative = false, PowOfTwo = false;
            unsigned SignBits = 0;
            while (CurTok.K != Token::ValName && CurTok.K != Token::Ident && CurTok.K != Token::Eof) {
                if (CurTok.K == Token::KnownBits) {
                    if (InstWidth != CurTok.PatternString.length()) {
                        ErrStr = makeErrStr(TP, "knownbits pattern must be of same length as var width");
                        return false;
                    }
                    for (unsigned i=0; i<InstWidth; ++i) {
                        if (CurTok.PatternString[i] == '0')
                            Zero += ConstOne.shl(CurTok.PatternString.length()-1-i);
                        else if (CurTok.PatternString[i] == '1')
                            One += ConstOne.shl(CurTok.PatternString.length()-1-i);
                    }
                    if (!consumeToken(ErrStr))
                        return false;
                }
                if (CurTok.K == Token::MoreKnownBits) {
                    for (unsigned i=0; i<CurTok.PatternString.length(); ++i) {
                        if (CurTok.PatternString[i] == 'z') {
                            if (NonZero) {
                                ErrStr = makeErrStr(TP, "repeated 'z' flag");
                                return false;
                            }
                            NonZero = true;
                        } else if (CurTok.PatternString[i] == 'n') {
                            if (NonNegative) {
                                ErrStr = makeErrStr(TP, "repeated 'n' flag");
                                return false;
                            }
                            NonNegative = true;
                        } else if (CurTok.PatternString[i] == 'p') {
                            if (PowOfTwo) {
                                ErrStr = makeErrStr(TP, "repeated 'p' flag");
                                return false;
                            }
                            PowOfTwo = true;
                        } else {
                            llvm_unreachable("nzp should have been checked earlier");
                        }
                    }
                    if (!consumeToken(ErrStr))
                        return false;
                }
            }
            Inst *I = IC.createVar(InstWidth, InstName, Zero, One, NonZero, NonNegative, PowOfTwo);
            Context.setInst(InstName, I);
            return true;
        }

        if (IK == Inst::Phi) {
            if (CurTok.K != Token::ValName) {
                ErrStr = makeErrStr("expected block number");
                return false;
            }
            if (CurTok.Width != 0) {
                ErrStr = makeErrStr("blocks may not have a width");
                return false;
            }
            if (!(B = Context.getBlock(CurTok.Name))) {
                ErrStr =
                    makeErrStr(std::string("%") + InstName.str() + " is not a block");
                return false;
            }
            if (!consumeToken(ErrStr)) return false;

            if (CurTok.K != Token::Comma) {
                ErrStr = makeErrStr("expected ','");
                return false;
            }
            if (!consumeToken(ErrStr)) return false;
        }

        std::vector<Inst *> Ops;

        while (1) {
            Inst *I = parseInst(ErrStr);
            if (!I)
                return false;

            Ops.push_back(I);

            if (CurTok.K != Token::Comma) break;
            if (!consumeToken(ErrStr)) return false;
        }

        Inst *I;
        if (IK == Inst::Phi) {
            assert(B);
            if (!typeCheckPhi(InstWidth, B, Ops, ErrStr)) {
                ErrStr = makeErrStr(TP, ErrStr);
                return false;
            }
            I = IC.getPhi(B, Ops);
        } else {
            if (!typeCheckInst(IK, InstWidth, Ops, ErrStr)) {
                ErrStr = makeErrStr(TP, ErrStr);
                return false;
            }
            switch (IK) {
            case Inst::SAddWithOverflow:
                I = IC.getInst(IK, InstWidth, {IC.getInst(Inst::Add, Ops[0]->Width, Ops),
                                               IC.getInst(Inst::SAddO, 1, Ops)
                                              });
                break;
            case Inst::UAddWithOverflow:
                I = IC.getInst(IK, InstWidth, {IC.getInst(Inst::Add, Ops[0]->Width, Ops),
                                               IC.getInst(Inst::UAddO, 1, Ops)
                                              });
                break;
            case Inst::SSubWithOverflow:
                I = IC.getInst(IK, InstWidth, {IC.getInst(Inst::Sub, Ops[0]->Width, Ops),
                                               IC.getInst(Inst::SSubO, 1, Ops)
                                              });
                break;
            case Inst::USubWithOverflow:
                I = IC.getInst(IK, InstWidth, {IC.getInst(Inst::Sub, Ops[0]->Width, Ops),
                                               IC.getInst(Inst::USubO, 1, Ops)
                                              });
                break;
            case Inst::SMulWithOverflow:
                I = IC.getInst(IK, InstWidth, {IC.getInst(Inst::Mul, Ops[0]->Width, Ops),
                                               IC.getInst(Inst::SMulO, 1, Ops)
                                              });
                break;
            case Inst::UMulWithOverflow:
                I = IC.getInst(IK, InstWidth, {IC.getInst(Inst::Mul, Ops[0]->Width, Ops),
                                               IC.getInst(Inst::UMulO, 1, Ops)
                                              });
                break;
            default:
                I = IC.getInst(IK, InstWidth, Ops);
                break;
            }
        }

        Context.setInst(InstName, I);
        return true;
    }

    default:
        ErrStr =
            makeErrStr("expected inst, block, cand, infer, result, pc, or blockpc");
        return false;
    }
}
void file_server::main(std::string file_name)
{
	std::string path;


	if(!check_in_document_root(file_name,path)) {
		show404();
		return;
	}
	
	int s=file_mode(path);
	
	if((s & S_IFDIR)) {
		std::string path2;
		int mode_2=0;
	
		bool have_index = check_in_document_root(file_name+"/" + index_file_ ,path2);
		if(have_index) {
			mode_2 = file_mode(path2);
			have_index = (mode_2  & S_IFREG) != 0;
		}

		if(     !file_name.empty() 
			&& file_name[file_name.size()-1]!='/'  // not ending with "/" as should
			&& (have_index || list_directories_)
		) 
		{
			response().set_redirect_header(file_name + "/");
			response().out()<<std::flush;
			return;
		}
		if(have_index) {
			path = path2;
			s=mode_2;
		}
		else {
			if(list_directories_) 
				list_dir(file_name,path);
			else
				show404();
			return;
		}

	}

	if(!(s & S_IFREG)) {
		show404();
		return;
	}
		
	std::string ext;
	size_t pos = path.rfind('.');
	if(pos != std::string::npos)
		ext=path.substr(pos);

	mime_type::const_iterator p=mime_.find(ext);
	if(p!=mime_.end()) 
		response().content_type(p->second);
	else
		response().content_type("application/octet-stream");

	if(!allow_deflate_) {
		response().io_mode(http::response::nogzip);
	}

	booster::nowide::ifstream file(path.c_str(),std::ios_base::binary);
	if(!file) {
		show404();
		return;
	}
	response().out()<<file.rdbuf(); // write stream to stream
}
Example #6
0
	bool hasLookupURL()
	{
		return !sLookupURL.empty();
	}
    void addCustomFunctionSource(const std::string& filename, const std::string& source) {
        CPPADCG_ASSERT_KNOWN(!filename.empty(), "The filename name cannot be empty");

        _customSource[filename] = source;
    }
Example #8
0
void FUGNetzteil::setError(std::string command, std::string error)
{
  if (error=="E0") return;
  lastError ="";
  lastError += boost::posix_time::to_iso_extended_string(boost::posix_time::second_clock::local_time());
  lastError +=" ";
  lastError += command;
  lastError += " ; ";
      error.erase( std::remove(error.begin(), error.end(), '\n'), error.end() );
  lastError += error;
    lastError += ": ";
  std::string discription;
  int errorNum;
    error.erase( std::remove(error.begin(), error.end(), 'E'), error.end() );
    
  if(!error.empty())
    errorNum = std::stoi (error);
  else
    errorNum = -1;
   
   if (errorNum == 1)
   {
   discription="keine Daten verfügbar";
    }
    else if (errorNum == 2)
   {
    discription="unbekannter Register-Typ";    
    }
    else if (errorNum == 4)
   {
    discription="ungültiges Argument";    
    }
        else if (errorNum == 5)
   {
    discription="Bereich überschritten";    
    }
    else if (errorNum == 6)
   {
    discription="Register darf nur gelesen werden";    
    }
      else if (errorNum == 7)
   {
    discription="Receive Overflow";    
    }
      else if (errorNum ==8 )
   {
    discription="EEPROM ist schreibgeschützt";    
    }
          else if (errorNum == 9)
   {
    discription="Adressfehler";    
    }
          else if (errorNum ==10 )
   {
    discription="unbekannter SCPI Befehl";    
    }
          else if (errorNum ==11 )
   {
    discription="Trigger on Talk Fehler";    
    }
              else if (errorNum ==12 )
   {
    discription="~Tn Befehl hatte ungültiges Argument";    
    }
              else if (errorNum ==13 )
   {
    discription="ungültiger N-Wert";    
    }
              else if (errorNum == 14)
   {
    discription="Register darf nurbeschrieben werden";    
    }
              else if (errorNum == 15)
   {
    discription="String zu lang";    
    }
              else if (errorNum == 101||errorNum == 102||errorNum == 103)
   {
    discription="Checksumme falsch";    
    }

else
   {
      discription="unbekannter Fehler";     
  }
   lastError += discription; 
  return;
}
Example #9
0
void
XMLSocket_as::checkForIncomingData()
{
    assert(ready());

    std::vector<std::string> msgs;

    const int bufSize = 10000;
    boost::scoped_array<char> buf(new char[bufSize]);

    const size_t bytesRead = _socket.readNonBlocking(buf.get(), bufSize - 1);

    // Return if there's no data.
    if (!bytesRead) return;

    if (buf[bytesRead - 1] != 0) {
        // We received a partial message, so bung
        // a null-terminator on the end.
        buf[bytesRead] = 0;
    }

    char* ptr = buf.get();
    while (static_cast<size_t>(ptr - buf.get()) < bytesRead) {

#ifdef GNASH_XMLSOCKET_DEBUG
        log_debug ("read: %d, this string ends: %d", bytesRead,
                   ptr + std::strlen(ptr) - buf.get());
#endif

        std::string msg(ptr);

        // If the string reaches to the final byte read, it's
        // incomplete. Store it and continue. The buffer is
        // NULL-terminated, so this cannot read past the end.
        if (static_cast<size_t>(
                    ptr + std::strlen(ptr) - buf.get()) == bytesRead) {
            _remainder += msg;
            break;
        }

        if (!_remainder.empty()) {
            msgs.push_back(_remainder + msg);
            ptr += msg.size() + 1;
            _remainder.clear();
            continue;
        }

        // Don't do anything if nothing is received.
        msgs.push_back(msg);

        ptr += msg.size() + 1;
    }

    if (msgs.empty()) return;

#ifdef GNASH_XMLSOCKET_DEBUG
    for (size_t i = 0, e = msgs.size(); i != e; ++i) {
        log_debug(_(" Message %d: %s "), i, msgs[i]);
    }
#endif

    for (XMLSocket_as::MessageList::const_iterator it=msgs.begin(),
            itEnd=msgs.end(); it != itEnd; ++it) {
        callMethod(&owner(), NSV::PROP_ON_DATA, *it);
    }

    if (_socket.bad()) {
        callMethod(&owner(), NSV::PROP_ON_CLOSE);
        close();
        return;
    }

}
SmartPtrCLogicalRelationshipDoc LogicalRelationshipXml::parse(
	const SmartPtrCXmlElement thisXml) {
	CAF_CM_STATIC_FUNC_VALIDATE("LogicalRelationshipXml", "parse");

	SmartPtrCLogicalRelationshipDoc logicalRelationshipDoc;

	CAF_CM_ENTER {
		CAF_CM_VALIDATE_SMARTPTR(thisXml);

		const std::string namespaceValStrVal =
			thisXml->findRequiredAttribute("namespace");
		const std::string namespaceValVal = namespaceValStrVal;

		const std::string nameStrVal =
			thisXml->findRequiredAttribute("name");
		const std::string nameVal = nameStrVal;

		const std::string versionStrVal =
			thisXml->findRequiredAttribute("version");
		const std::string versionVal = versionStrVal;

		const std::string arityStrVal =
			thisXml->findRequiredAttribute("arity");
		ARITY_TYPE arityVal = ARITY_NONE;
		if (! arityStrVal.empty()) {
			arityVal = EnumConvertersXml::convertStringToArityType(arityStrVal);
		}

		const SmartPtrCXmlElement dataClassLeftXml =
			thisXml->findRequiredChild("dataClassLeft");

		SmartPtrCClassCardinalityDoc dataClassLeftVal;
		if (! dataClassLeftXml.IsNull()) {
			dataClassLeftVal = ClassCardinalityXml::parse(dataClassLeftXml);
		}

		const SmartPtrCXmlElement dataClassRightXml =
			thisXml->findRequiredChild("dataClassRight");

		SmartPtrCClassCardinalityDoc dataClassRightVal;
		if (! dataClassRightXml.IsNull()) {
			dataClassRightVal = ClassCardinalityXml::parse(dataClassRightXml);
		}

		const CXmlElement::SmartPtrCElementCollection joinChildrenXml =
			thisXml->findRequiredChildren("join");

		std::deque<SmartPtrCJoinTypeDoc> joinVal;
		if (! joinChildrenXml.IsNull() && ! joinChildrenXml->empty()) {
			for (TConstIterator<CXmlElement::CElementCollection> joinXmlIter(*joinChildrenXml);
				joinXmlIter; joinXmlIter++) {
				const SmartPtrCXmlElement joinXml = joinXmlIter->second;
				const SmartPtrCJoinTypeDoc joinDoc =
					JoinTypeXml::parse(joinXml);
				joinVal.push_back(joinDoc);
			}
		}

		const std::string descriptionStrVal =
			thisXml->findOptionalAttribute("description");
		const std::string descriptionVal = descriptionStrVal;

		logicalRelationshipDoc.CreateInstance();
		logicalRelationshipDoc->initialize(
			namespaceValVal,
			nameVal,
			versionVal,
			arityVal,
			dataClassLeftVal,
			dataClassRightVal,
			joinVal,
			descriptionVal);
	}
	CAF_CM_EXIT;

	return logicalRelationshipDoc;
}
/* ****************************************************************************
*
* httpRequestSendWithCurl -
*
* The waitForResponse arguments specifies if the method has to wait for response
* before return. If this argument is false, the return string is ""
*
* NOTE
* We are using a hybrid approach, consisting in a static thread-local buffer of a
* small size that copes with most notifications to avoid expensive
* calloc/free syscalls if the notification payload is not very large.
*
* RETURN VALUES
*   httpRequestSendWithCurl returns 0 on success and a negative number on failure:
*     -1: Invalid port
*     -2: Invalid IP
*     -3: Invalid verb
*     -4: Invalid resource
*     -5: No Content-Type BUT content present
*     -6: Content-Type present but there is no content
*     -7: Total outgoing message size is too big
*     -9: Error making HTTP request
*/
int httpRequestSendWithCurl
(
   CURL                   *curl,
   const std::string&     _ip,
   unsigned short         port,
   const std::string&     protocol,
   const std::string&     verb,
   const std::string&     tenant,
   const std::string&     servicePath,
   const std::string&     xauthToken,
   const std::string&     resource,
   const std::string&     orig_content_type,
   const std::string&     content,
   bool                   useRush,
   bool                   waitForResponse,
   std::string*           outP,
   const std::string&     acceptFormat,
   long                   timeoutInMilliseconds
)
{
  char                       portAsString[STRING_SIZE_FOR_INT];
  static unsigned long long  callNo             = 0;
  std::string                result;
  std::string                ip                 = _ip;
  struct curl_slist*         headers            = NULL;
  MemoryStruct*              httpResponse       = NULL;
  CURLcode                   res;
  int                        outgoingMsgSize       = 0;
  std::string                content_type(orig_content_type);

  ++callNo;

  // For content-type application/json we add charset=utf-8
  if (orig_content_type == "application/json")
  {
    content_type += "; charset=utf-8";
  }

  if (timeoutInMilliseconds == -1)
  {
    timeoutInMilliseconds = defaultTimeout;
  }

  lmTransactionStart("to", ip.c_str(), port, resource.c_str());

  // Preconditions check
  if (port == 0)
  {
    LM_E(("Runtime Error (port is ZERO)"));
    lmTransactionEnd();

    *outP = "error";
    return -1;
  }

  if (ip.empty())
  {
    LM_E(("Runtime Error (ip is empty)"));
    lmTransactionEnd();

    *outP = "error";
    return -2;
  }

  if (verb.empty())
  {
    LM_E(("Runtime Error (verb is empty)"));
    lmTransactionEnd();

    *outP = "error";
    return -3;
  }

  if (resource.empty())
  {
    LM_E(("Runtime Error (resource is empty)"));
    lmTransactionEnd();

    *outP = "error";
    return -4;
  }

  if ((content_type.empty()) && (!content.empty()))
  {
    LM_E(("Runtime Error (Content-Type is empty but there is actual content)"));
    lmTransactionEnd();

    *outP = "error";
    return -5;
  }

  if ((!content_type.empty()) && (content.empty()))
  {
    LM_E(("Runtime Error (Content-Type non-empty but there is no content)"));
    lmTransactionEnd();

    *outP = "error";
    return -6;
  }



  // Allocate to hold HTTP response
  httpResponse = new MemoryStruct;
  httpResponse->memory = (char*) malloc(1); // will grow as needed
  httpResponse->size = 0; // no data at this point

  //
  // Rush
  // Every call to httpRequestSend specifies whether RUSH should be used or not.
  // But, this depends also on how the broker was started, so here the 'useRush'
  // parameter is cancelled in case the broker was started without rush.
  //
  // If rush is to be used, the IP/port is stored in rushHeaderIP/rushHeaderPort and
  // after that, the host and port of rush is set as ip/port for the message, that is
  // now sent to rush instead of to its final destination.
  // Also, a few HTTP headers for rush must be setup.
  //
  if ((rushPort == 0) || (rushHost == ""))
  {
    useRush = false;
  }

  if (useRush)
  {
    char         rushHeaderPortAsString[STRING_SIZE_FOR_INT];
    uint16_t     rushHeaderPort     = port;
    std::string  rushHeaderIP       = ip;
    std::string  headerRushHttp;

    ip    = rushHost;
    port  = rushPort;

    snprintf(rushHeaderPortAsString, sizeof(rushHeaderPortAsString), "%d", rushHeaderPort);
    headerRushHttp = "X-relayer-host: " + rushHeaderIP + ":" + rushHeaderPortAsString;
    LM_T(LmtHttpHeaders, ("HTTP-HEADERS: '%s'", headerRushHttp.c_str()));
    headers = curl_slist_append(headers, headerRushHttp.c_str());
    outgoingMsgSize += headerRushHttp.size();

    if (protocol == "https:")
    {
      headerRushHttp = "X-relayer-protocol: https";
      LM_T(LmtHttpHeaders, ("HTTP-HEADERS: '%s'", headerRushHttp.c_str()));
      headers = curl_slist_append(headers, headerRushHttp.c_str());
      outgoingMsgSize += headerRushHttp.size();
    }
  }

  snprintf(portAsString, sizeof(portAsString), "%u", port);

  // ----- User Agent
  char cvBuf[CURL_VERSION_MAX_LENGTH];
  char headerUserAgent[HTTP_HEADER_USER_AGENT_MAX_LENGTH];

  snprintf(headerUserAgent, sizeof(headerUserAgent), "User-Agent: orion/%s libcurl/%s", versionGet(), curlVersionGet(cvBuf, sizeof(cvBuf)));
  LM_T(LmtHttpHeaders, ("HTTP-HEADERS: '%s'", headerUserAgent));
  headers = curl_slist_append(headers, headerUserAgent);
  outgoingMsgSize += strlen(headerUserAgent) + 1;

  // ----- Host
  char headerHost[HTTP_HEADER_HOST_MAX_LENGTH];

  snprintf(headerHost, sizeof(headerHost), "Host: %s:%d", ip.c_str(), (int) port);
  LM_T(LmtHttpHeaders, ("HTTP-HEADERS: '%s'", headerHost));
  headers = curl_slist_append(headers, headerHost);
  outgoingMsgSize += strlen(headerHost) + 1;

  // ----- Tenant
  if (tenant != "")
  {
    headers = curl_slist_append(headers, ("fiware-service: " + tenant).c_str());
    outgoingMsgSize += tenant.size() + 16; // "fiware-service: "
  }

  // ----- Service-Path
  if (servicePath != "")
  {
    headers = curl_slist_append(headers, ("Fiware-ServicePath: " + servicePath).c_str());
    outgoingMsgSize += servicePath.size() + strlen("Fiware-ServicePath: ");
  }

  // ----- X-Auth-Token
  if (xauthToken != "")
  {
    headers = curl_slist_append(headers, ("X-Auth-Token: " + xauthToken).c_str());
    outgoingMsgSize += xauthToken.size() + strlen("X-Auth-Token: ");
  }

  // ----- Accept
  std::string acceptedFormats = "application/xml, application/json";
  if (acceptFormat != "")
  {
    acceptedFormats = acceptFormat;
  }

  std::string acceptString = "Accept: " + acceptedFormats;
  headers = curl_slist_append(headers, acceptString.c_str());
  outgoingMsgSize += acceptString.size();

  // ----- Expect
  headers = curl_slist_append(headers, "Expect: ");
  outgoingMsgSize += 8; // from "Expect: "

  // ----- Content-length
  std::stringstream contentLengthStringStream;
  contentLengthStringStream << content.size();
  std::string headerContentLength = "Content-length: " + contentLengthStringStream.str();
  LM_T(LmtHttpHeaders, ("HTTP-HEADERS: '%s'", headerContentLength.c_str()));
  headers = curl_slist_append(headers, headerContentLength.c_str());
  outgoingMsgSize += contentLengthStringStream.str().size() + 16; // from "Content-length: "
  outgoingMsgSize += content.size();

  // ----- Content-type
  headers = curl_slist_append(headers, ("Content-type: " + content_type).c_str());
  outgoingMsgSize += content_type.size() + 14; // from "Content-type: "


  // Check if total outgoing message size is too big
  if (outgoingMsgSize > MAX_DYN_MSG_SIZE)
  {
    LM_E(("Runtime Error (HTTP request to send is too large: %d bytes)", outgoingMsgSize));

    curl_slist_free_all(headers);

    free(httpResponse->memory);
    delete httpResponse;

    lmTransactionEnd();
    *outP = "error";
    return -7;
  }

  // Contents
  const char* payload = content.c_str();
  curl_easy_setopt(curl, CURLOPT_POSTFIELDS, (u_int8_t*) payload);

  // Set up URL
  std::string url;
  if (isIPv6(ip))
    url = "[" + ip + "]";
  else
    url = ip;
  url = url + ":" + portAsString + (resource.at(0) == '/'? "" : "/") + resource;

  // Prepare CURL handle with obtained options
  curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, verb.c_str()); // Set HTTP verb
  curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); // Allow redirection (?)
  curl_easy_setopt(curl, CURLOPT_HEADER, 1); // Activate include the header in the body output
  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); // Put headers in place
  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &writeMemoryCallback); // Send data here
  curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*) httpResponse); // Custom data for response handling

  //
  // There is a known problem in libcurl (see http://stackoverflow.com/questions/9191668/error-longjmp-causes-uninitialized-stack-frame)
  // which is solved using CURLOPT_NOSIGNAL. If we update some day from libcurl 7.19 (the one that comes with CentOS 6.x) to a newer version
  // (there are some reports about the bug is no longer in libcurl 7.32), using CURLOPT_NOSIGNAL could be not necessary and this be removed).
  // See issue #1016 for more details.
  //
  curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);

  //
  // Timeout 
  //
  // The parameter timeoutInMilliseconds holds the timeout time in milliseconds.
  // If the timeout time requested is 0, then no timeuot is used.
  //
  if (timeoutInMilliseconds != 0) 
  {
    curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, timeoutInMilliseconds);
  }


  // Synchronous HTTP request
  LM_T(LmtClientOutputPayload, ("Sending message %lu to HTTP server: sending message of %d bytes to HTTP server", callNo, outgoingMsgSize));
  res = curl_easy_perform(curl);

  if (res != CURLE_OK)
  {
    //
    // NOTE: This log line is used by the functional tests in cases/880_timeout_for_forward_and_notifications/
    //       So, this line should not be removed/altered, at least not without also modifying the functests.
    //    
    alarmMgr.notificationError(url, "(curl_easy_perform failed: " + std::string(curl_easy_strerror(res)) + ")");
    *outP = "notification failure";
  }
  else
  {
    // The Response is here
    LM_I(("Notification Successfully Sent to %s", url.c_str()));
    outP->assign(httpResponse->memory, httpResponse->size);
  }

  // Cleanup curl environment

  curl_slist_free_all(headers);

  free(httpResponse->memory);
  delete httpResponse;

  lmTransactionEnd();

  return res == CURLE_OK ? 0 : -9;
}
void LogicalRelationshipXml::add(
	const SmartPtrCLogicalRelationshipDoc logicalRelationshipDoc,
	const SmartPtrCXmlElement thisXml) {
	CAF_CM_STATIC_FUNC_VALIDATE("LogicalRelationshipXml", "add");

	CAF_CM_ENTER {
		CAF_CM_VALIDATE_SMARTPTR(logicalRelationshipDoc);
		CAF_CM_VALIDATE_SMARTPTR(thisXml);

		const std::string namespaceValVal = logicalRelationshipDoc->getNamespaceVal();
		CAF_CM_VALIDATE_STRING(namespaceValVal);
		thisXml->addAttribute("namespace", namespaceValVal);

		const std::string nameVal = logicalRelationshipDoc->getName();
		CAF_CM_VALIDATE_STRING(nameVal);
		thisXml->addAttribute("name", nameVal);

		const std::string versionVal = logicalRelationshipDoc->getVersion();
		CAF_CM_VALIDATE_STRING(versionVal);
		thisXml->addAttribute("version", versionVal);

		const std::string arityVal =
			EnumConvertersXml::convertArityTypeToString(logicalRelationshipDoc->getArity());
		CAF_CM_VALIDATE_STRING(arityVal);
		thisXml->addAttribute("arity", arityVal);

		const SmartPtrCClassCardinalityDoc dataClassLeftVal =
			logicalRelationshipDoc->getDataClassLeft();
		CAF_CM_VALIDATE_SMARTPTR(dataClassLeftVal);

		const SmartPtrCXmlElement dataClassLeftXml =
			thisXml->createAndAddElement("dataClassLeft");
		ClassCardinalityXml::add(dataClassLeftVal, dataClassLeftXml);

		const SmartPtrCClassCardinalityDoc dataClassRightVal =
			logicalRelationshipDoc->getDataClassRight();
		CAF_CM_VALIDATE_SMARTPTR(dataClassRightVal);

		const SmartPtrCXmlElement dataClassRightXml =
			thisXml->createAndAddElement("dataClassRight");
		ClassCardinalityXml::add(dataClassRightVal, dataClassRightXml);

		const std::deque<SmartPtrCJoinTypeDoc> joinVal =
			logicalRelationshipDoc->getJoinCollection();
		CAF_CM_VALIDATE_STL(joinVal);

		if (! joinVal.empty()) {
			for (TConstIterator<std::deque<SmartPtrCJoinTypeDoc> > joinIter(joinVal);
				joinIter; joinIter++) {
				const SmartPtrCXmlElement joinXml =
					thisXml->createAndAddElement("join");
				JoinTypeXml::add(*joinIter, joinXml);
			}
		}

		const std::string descriptionVal = logicalRelationshipDoc->getDescription();
		if (! descriptionVal.empty()) {
			thisXml->addAttribute("description", descriptionVal);
		}
	}
	CAF_CM_EXIT;
}
Example #13
0
    static bool table_info(std::string & key_field,
                           bool detected_types,
                           std::string & field,
                           std::string & table,
                           mapnik::layer_descriptor & desc,
                           boost::shared_ptr<sqlite_connection> ds)
    {

        // http://www.sqlite.org/pragma.html#pragma_table_info
        // use pragma table_info to detect primary key
        // and to detect types if no subquery is used or
        // if the subquery-based type detection failed
        std::ostringstream s;
        s << "PRAGMA table_info(" << table << ")";
        boost::shared_ptr<sqlite_resultset> rs(ds->execute_query(s.str()));
        bool found_table = false;
        bool found_pk = false;
        while (rs->is_valid() && rs->step_next())
        {
            found_table = true;
            const char* fld_name = rs->column_text(1);
            std::string fld_type(rs->column_text(2));
            int fld_pk = rs->column_integer(5);
            boost::algorithm::to_lower(fld_type);

            // TODO - how to handle primary keys on multiple columns ?
            if (key_field.empty() && ! found_pk && fld_pk != 0)
            {
                key_field = fld_name;
                found_pk = true;
            }
            if (! detected_types)
            {
                // see 2.1 "Column Affinity" at http://www.sqlite.org/datatype3.html
                // TODO - refactor this somehow ?
                if (field.empty()
                    && ((boost::algorithm::contains(fld_type, "geom") ||
                         boost::algorithm::contains(fld_type, "point") ||
                         boost::algorithm::contains(fld_type, "linestring") ||
                         boost::algorithm::contains(fld_type, "polygon"))
                        ||
                        (boost::algorithm::icontains(fld_name, "geom") ||
                         boost::algorithm::icontains(fld_name, "point") ||
                         boost::algorithm::icontains(fld_name, "linestring") ||
                         boost::algorithm::icontains(fld_name, "polygon")))
                    )
                {
                    field = std::string(fld_name);
                }
                else if (boost::algorithm::contains(fld_type, "int"))
                {
                    desc.add_descriptor(mapnik::attribute_descriptor(fld_name, mapnik::Integer));
                }
                else if (boost::algorithm::contains(fld_type, "text") ||
                         boost::algorithm::contains(fld_type, "char") ||
                         boost::algorithm::contains(fld_type, "clob"))
                {
                    desc.add_descriptor(mapnik::attribute_descriptor(fld_name, mapnik::String));
                }
                else if (boost::algorithm::contains(fld_type, "real") ||
                         boost::algorithm::contains(fld_type, "float") ||
                         boost::algorithm::contains(fld_type, "double"))
                {
                    desc.add_descriptor(mapnik::attribute_descriptor(fld_name, mapnik::Double));
                }
                else if (boost::algorithm::contains(fld_type, "blob"))
                {
                    if (! field.empty())
                    {
                        desc.add_descriptor(mapnik::attribute_descriptor(fld_name, mapnik::String));
                    }
                }
#ifdef MAPNIK_DEBUG
                else
                {
                    // "Column Affinity" says default to "Numeric" but for now we pass..
                    //desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double));

                    // TODO - this should not fail when we specify geometry_field in XML file

                    std::clog << "Sqlite Plugin: column '"
                              << std::string(fld_name)
                              << "' unhandled due to unknown type: "
                              << fld_type << std::endl;
                }
#endif
            }
        }

        return found_table;
    }
bool CGUIWindowAddonBrowser::GetDirectory(const std::string& strDirectory, CFileItemList& items)
{
  bool result;
  if (URIUtils::PathEquals(strDirectory, "addons://downloading/"))
  {
    VECADDONS addons;
    CAddonInstaller::GetInstance().GetInstallList(addons);

    CURL url(strDirectory);
    CAddonsDirectory::GenerateAddonListing(url, addons, items, g_localizeStrings.Get(24067));
    result = true;
    items.SetPath(strDirectory);

    if (m_guiState.get() && !m_guiState->HideParentDirItems())
    {
      CFileItemPtr pItem(new CFileItem(".."));
      pItem->SetPath(m_history.GetParentPath());
      pItem->m_bIsFolder = true;
      pItem->m_bIsShareOrDrive = false;
      items.AddFront(pItem, 0);
    }

  }
  else
  {
    result = CGUIMediaWindow::GetDirectory(strDirectory, items);

    if (result && CAddonsDirectory::IsRepoDirectory(CURL(strDirectory)))
    {
      if (CSettings::GetInstance().GetBool(CSettings::SETTING_GENERAL_ADDONFOREIGNFILTER))
      {
        int i = 0;
        while (i < items.Size())
        {
          auto prop = items[i]->GetProperty("Addon.Language");
          if (!prop.isNull() && IsForeign(prop.asString()))
            items.Remove(i);
          else
            ++i;
        }
      }
      if (CSettings::GetInstance().GetBool(CSettings::SETTING_GENERAL_ADDONBROKENFILTER))
      {
        for (int i = items.Size() - 1; i >= 0; i--)
        {
          if (!items[i]->GetProperty("Addon.Broken").empty())
          {
            //check if it's installed
            AddonPtr addon;
            if (!CAddonMgr::GetInstance().GetAddon(items[i]->GetProperty("Addon.ID").asString(), addon))
              items.Remove(i);
          }
        }
      }
    }
  }

  if (strDirectory.empty() && CAddonInstaller::GetInstance().IsDownloading())
  {
    CFileItemPtr item(new CFileItem("addons://downloading/", true));
    item->SetLabel(g_localizeStrings.Get(24067));
    item->SetLabelPreformated(true);
    item->SetIconImage("DefaultNetwork.png");
    items.Add(item);
  }

  items.SetContent("addons");

  for (int i = 0; i < items.Size(); ++i)
    SetItemLabel2(items[i]);

  return result;
}
Example #15
0
void WfutSession::startUpdate(const std::string &serverRoot,
const std::string &channelName,
const std::string &localPath,
const std::string &systemPath
)
{
	
	S_LOG_VERBOSE("Channel name: " << channelName);
	// This is the base path for all files that will be downloaded
	const std::string local_root = localPath + "/" + channelName + "/";
	
	std::string channel(channelName);
	std::string channel_file = "wfut.xml";
	std::string tmpfile = "tempwfut.xml";
	
	// Look for mLocal mWfutClient file.
	mLocalWfut = std::string(localPath  + "/" + channelName + "/" + channel_file);
	S_LOG_VERBOSE("Local wfut: " << mLocalWfut);
	if (fileExists(mLocalWfut)) {
		if (mWfutClient.getLocalList(mLocalWfut, mLocal)) {
			S_LOG_WARNING("Error reading local wfut.xml file.");
		}
	}
	
	// Look for tmpwfut file. If it exists, update the mLocal files list.
	const std::string tmp_wfut = localPath  + "/" + tmpfile;
	S_LOG_VERBOSE("Tmp wfut: " << tmp_wfut);
	
	if (fileExists(tmp_wfut)) {
		if (mWfutClient.getLocalList(tmp_wfut, mTmplist)) {
			S_LOG_WARNING("Error reading local tmpwfut.xml file.");
		} else {
			const FileMap &fm = mTmplist.getFiles();
			FileMap::const_iterator I = fm.begin();
			FileMap::const_iterator Iend = fm.end();
			for (; I != Iend; ++I) {
				mLocal.addFile(I->second);
			}
		}
	}
	
	
	// Look for a mSystem mWfutClient file
	if (!systemPath.empty()) {
		const std::string system_wfut = systemPath + "/" + channel + "/" + channel_file; 
		S_LOG_VERBOSE("System wfut: " << system_wfut);
		
		if (fileExists(system_wfut)) {
			if (mWfutClient.getLocalList(system_wfut, mSystem)) {
				S_LOG_WARNING("Error reading system wfut.xml file.");
			}
		}
	}
	
	// By now we should have a proper channel name. If not, then there is nothing 
	// we can do to find the mServer mUpdates.
	if (channel.empty() || channel == ".") {
		S_LOG_WARNING("Unable to determine channel name.");
		return;
	}
	
	const std::string server_wfut = serverRoot + "/" + channel + "/" + channel_file; 
	S_LOG_VERBOSE("Server wfut: " << server_wfut);
	
	mServerListDownloadingSlot(server_wfut);
	if (mWfutClient.getFileList(server_wfut, mServer)) {
		S_LOG_WARNING("Error downloading server channel file.");
		return;
	}
	
	S_LOG_VERBOSE("Local Root: " << local_root);
	
	S_LOG_INFO("Updating Channel: " << channel);
	
	// Now we have loaded all our data files, lets find out what we really need
	// to download
	if (mWfutClient.calculateUpdates(mServer, mSystem, mLocal, mUpdates, local_root)) {
		S_LOG_WARNING("Error determining file to update.");
		return;
	}
	
	mUpdatesCalculatedSlot(mUpdates.getFiles().size());
	
	// Make sure the mLocal file has the correct channel name
	mLocal.setName(mServer.getName());
	
	// Queue the list of files to download
	mWfutClient.updateChannel(mUpdates, serverRoot + "/" + channel, local_root);
	
}
    int create_listener (
        listener*& new_listener,
        unsigned short port,
        const std::string& ip
    )
    {
        // ensure that WSAStartup has been called and WSACleanup will eventually 
        // be called when program ends
        sockets_startup();

        sockaddr_in sa;  // local socket structure
        ZeroMemory(&sa,sizeof(sockaddr_in)); // initialize sa

        SOCKET sock = socket (AF_INET, SOCK_STREAM, 0);  // get a new socket

        // if socket() returned an error then return OTHER_ERROR
        if (sock == INVALID_SOCKET )
        {
            return OTHER_ERROR;
        }

        // set the local socket structure 
        sa.sin_family = AF_INET;
        sa.sin_port = htons(port);
        if (ip.empty())
        {            
            // if the listener should listen on any IP
            sa.sin_addr.S_un.S_addr = htons(INADDR_ANY);
        }
        else
        {
            // if there is a specific ip to listen on
            sa.sin_addr.S_un.S_addr = inet_addr(ip.c_str());
            // if inet_addr cound't convert the ip then return an error
            if ( sa.sin_addr.S_un.S_addr == INADDR_NONE )
            {
                closesocket(sock); 
                return OTHER_ERROR;                
            }
        }

        // set the SO_REUSEADDR option
        int flag_value = 1;
        setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,reinterpret_cast<const char*>(&flag_value),sizeof(int));

        // bind the new socket to the requested port and ip
        if (bind(sock,reinterpret_cast<sockaddr*>(&sa),sizeof(sockaddr_in))==SOCKET_ERROR)
        {   // if there was an error 
            closesocket(sock); 

            // if the port is already bound then return PORTINUSE
            if (WSAGetLastError() == WSAEADDRINUSE)
                return PORTINUSE;
            else
                return OTHER_ERROR;            
        }


        // tell the new socket to listen
        if ( listen(sock,SOMAXCONN) == SOCKET_ERROR)
        {
            // if there was an error return OTHER_ERROR
            closesocket(sock); 

            // if the port is already bound then return PORTINUSE
            if (WSAGetLastError() == WSAEADDRINUSE)
                return PORTINUSE;
            else
                return OTHER_ERROR;  
        }

        // determine the port used if necessary
        if (port == 0)
        {
            sockaddr_in local_info;
            int length = sizeof(sockaddr_in);
            if ( getsockname (
                        sock,
                        reinterpret_cast<sockaddr*>(&local_info),
                        &length
                 ) == SOCKET_ERROR
            )
            {
                closesocket(sock);
                return OTHER_ERROR;
            }
            port = ntohs(local_info.sin_port);            
        }


        // initialize a listener object on the heap with the new socket
        try { new_listener = new listener(sock,port,ip); }
        catch(...) { closesocket(sock); return OTHER_ERROR; }

        return 0;
    }
Example #17
0
    bool
    BasicModem::processInput(std::string& str)
    {
      bool got_line = false;

      while (!m_chars.empty())
      {
        char c = m_chars.front();
        m_chars.pop();

          m_line.push_back(c);

        //!@fixme: concurrency hazard.
        if (c == m_line_term_in[m_line_term_idx])
        {
          ++m_line_term_idx;
          if (m_line_term_idx == m_line_term_in.size())
          {
            m_line_term_idx = 0;
            got_line = true;
            break;
          }
        }
        else
        {

        }
      }

      if (isFragment(m_line))
      {
        getTask()->inf(DTR("fragment: %s"), Streams::sanitize(m_line).c_str());
        return false;
      }

      // No complete line is available.
      if (!got_line)
        return false;

      if (m_line.size() <= m_line_term_in.size())
      {
        str = "";
        return true;
      }

      // Remove termination characters.
      str = m_line;
      str.resize(m_line.size() - m_line_term_in.size());

      if (m_line_trim)
        str = Utils::String::trim(str);

      // Got a complete line, but it's empty.
      if (str.empty())
        return true;

      m_task->spew("recv: %s", Streams::sanitize(str).c_str());
      m_line.clear();

      if (!m_skip_line.empty())
      {
        if (m_skip_line == str)
        {
          str.clear();
          m_skip_line.clear();
        }
      }

      return true;
    }
    int create_connection ( 
        connection*& new_connection,
        unsigned short foreign_port, 
        const std::string& foreign_ip, 
        unsigned short local_port,
        const std::string& local_ip
    )
    {
        // ensure that WSAStartup has been called and WSACleanup 
        // will eventually be called when program ends
        sockets_startup();


        sockaddr_in local_sa;  // local socket structure
        sockaddr_in foreign_sa;  // foreign socket structure
        ZeroMemory(&local_sa,sizeof(sockaddr_in)); // initialize local_sa
        ZeroMemory(&foreign_sa,sizeof(sockaddr_in)); // initialize foreign_sa

        int length;

        SOCKET sock = socket (AF_INET, SOCK_STREAM, 0);  // get a new socket

        // if socket() returned an error then return OTHER_ERROR
        if (sock == INVALID_SOCKET )
        {
            return OTHER_ERROR;
        }

        // set the foreign socket structure 
        foreign_sa.sin_family = AF_INET;
        foreign_sa.sin_port = htons(foreign_port);
        foreign_sa.sin_addr.S_un.S_addr = inet_addr(foreign_ip.c_str());

        // if inet_addr cound't convert the ip then return an error
        if ( foreign_sa.sin_addr.S_un.S_addr == INADDR_NONE )
        {
            closesocket(sock);
            return OTHER_ERROR;
        }


        // set up the local socket structure
        local_sa.sin_family = AF_INET;

        // set the local ip
        if (local_ip.empty())
        {            
            // if the listener should listen on any IP
            local_sa.sin_addr.S_un.S_addr = htons(INADDR_ANY);
        }
        else
        {
            // if there is a specific ip to listen on
            local_sa.sin_addr.S_un.S_addr = inet_addr(local_ip.c_str());   

            // if inet_addr couldn't convert the ip then return an error
            if (local_sa.sin_addr.S_un.S_addr == INADDR_NONE)
            {
                closesocket(sock);
                return OTHER_ERROR;
            }
        }

        // set the local port
        local_sa.sin_port = htons(local_port);

        

        // bind the new socket to the requested local port and local ip
        if ( bind (
                sock,
                reinterpret_cast<sockaddr*>(&local_sa),
                sizeof(sockaddr_in)
            ) == SOCKET_ERROR
        )
        {   // if there was an error 
            closesocket(sock); 

            // if the port is already bound then return PORTINUSE
            if (WSAGetLastError() == WSAEADDRINUSE)
                return PORTINUSE;
            else
                return OTHER_ERROR;            
        }

        // connect the socket        
        if (connect (
                sock,
                reinterpret_cast<sockaddr*>(&foreign_sa),
                sizeof(sockaddr_in)
            ) == SOCKET_ERROR
        )
        {
            closesocket(sock); 
            // if the port is already bound then return PORTINUSE
            if (WSAGetLastError() == WSAEADDRINUSE)
                return PORTINUSE;
            else
                return OTHER_ERROR;  
        }



        // determine the local port and IP and store them in used_local_ip 
        // and used_local_port
        int used_local_port;
        std::string used_local_ip;
        sockaddr_in local_info;
        if (local_port == 0)
        {
            length = sizeof(sockaddr_in);
            if (getsockname (
                    sock,
                    reinterpret_cast<sockaddr*>(&local_info),
                    &length
                ) == SOCKET_ERROR
            )
            {
                closesocket(sock);
                return OTHER_ERROR;
            }
            used_local_port = ntohs(local_info.sin_port);            
        }
        else
        {
            used_local_port = local_port;
        }

        // determine real local ip
        if (local_ip.empty())
        {
            // if local_port is not 0 then we must fill the local_info structure
            if (local_port != 0)
            {
                length = sizeof(sockaddr_in);
                if ( getsockname (
                        sock,
                        reinterpret_cast<sockaddr*>(&local_info),
                        &length
                    ) == SOCKET_ERROR 
                )
                {
                    closesocket(sock);
                    return OTHER_ERROR;
                }
            }
            char* temp = inet_ntoa(local_info.sin_addr);

            // check if inet_ntoa returned an error
            if (temp == NULL)
            {
                closesocket(sock);
                return OTHER_ERROR;            
            }
            used_local_ip.assign(temp);
        }
        else
        {
            used_local_ip = local_ip;
        }

        // set the SO_OOBINLINE option
        int flag_value = 1;
        if (setsockopt(sock,SOL_SOCKET,SO_OOBINLINE,reinterpret_cast<const char*>(&flag_value),sizeof(int)) == SOCKET_ERROR )
        {
            closesocket(sock);
            return OTHER_ERROR;  
        }

        // initialize a connection object on the heap with the new socket
        try 
        { 
            new_connection = new connection (
                                    sock,
                                    foreign_port,
                                    foreign_ip,
                                    used_local_port,
                                    used_local_ip
                                ); 
        }
        catch(...) {closesocket(sock);  return OTHER_ERROR; }

        return 0;
    }
Example #19
0
int main( int ac, char** av )
{
    try
    {
        comma::command_line_options options( ac, av );
        verbose = options.exists( "--verbose,-v" );
        debug = options.exists( "--debug" );
        append = options.exists( "--append,-a" );
        if( options.exists( "--help,-h" ) ) { usage( verbose ); }
        if( options.exists( "--input-fields" ) ) { std::cout << comma::join( comma::csv::names< interval_t< double > >(), ',' ) << std::endl; return 0; }
        if( options.exists( "--output-fields" ) ) { std::cout << comma::join( comma::csv::names< interval_t< double > >(), ',' ) << std::endl; return 0; }
        comma::csv::options csv( options );
        if( csv.fields.empty() ) { csv.fields = comma::join( comma::csv::names< interval_t< double > >(), ',' ); }
        if( !csv.has_field( "from,to" ) ) { COMMA_THROW( comma::exception, "expected from and to fields" ); }
        options.assert_mutually_exclusive( "--binary,--format" );
        if( options.exists( "--binary,-b" ) ) {}
        else if( options.exists( "--format" ) ) { csv.format( options.value< std::string >( "--format" ) ); }
        else
        {
            while( std::cin.good() && first_line.empty() ) { std::getline( std::cin, first_line ); }
            if( first_line.empty() ) { return 0; }
            csv.format( comma::csv::impl::unstructured::guess_format( first_line, csv.delimiter ) );
            if( verbose ) { std::cerr << app_name << ": guessed format: " << csv.format().string() << std::endl;; }
        }
        const std::vector< std::string >& fields = comma::split( csv.fields, ',' );
        unsigned int from_index = 0;
        unsigned int to_index = 1;
        for( unsigned int i = 0; i < fields.size(); ++i ) { if( fields[i] == "from" ) { from_index = i; break; } }
        for( unsigned int i = 0; i < fields.size(); ++i ) { if( fields[i] == "to" ) { to_index = i; break; } }
        const comma::csv::format::types_enum from_type = csv.format().offset( from_index ).type;
        const comma::csv::format::types_enum to_type = csv.format().offset( to_index ).type;
        if( ( ( from_type == comma::csv::format::time || from_type == comma::csv::format::long_time ) && ( to_type != comma::csv::format::time && to_type != comma::csv::format::long_time ) ) ||
          ( ( ( from_type != comma::csv::format::time && from_type != comma::csv::format::long_time ) && ( to_type == comma::csv::format::time || to_type == comma::csv::format::long_time ) ) ) )
        { COMMA_THROW( comma::exception, "from/to type mismatch; time" ); }
        if( ( from_type == comma::csv::format::fixed_string || to_type == comma::csv::format::fixed_string ) && from_type != to_type )
        { COMMA_THROW( comma::exception, "from/to type mismatch; string" ); }
//         switch( from_type )
//         {
//             case comma::csv::format::int8:          run< char >( options, to_type ); break;
//             case comma::csv::format::uint8:         run< unsigned char >( options, to_type ); break;
//             case comma::csv::format::int16:         run< comma::int16 >( options, to_type ); break;
//             case comma::csv::format::uint16:        run< comma::uint16 >( options, to_type ); break;
//             case comma::csv::format::int32:         run< comma::int32 >( options, to_type ); break;
//             case comma::csv::format::uint32:        run< comma::uint32 >( options, to_type ); break;
//             case comma::csv::format::int64:         run< comma::int64 >( options, to_type ); break;
//             case comma::csv::format::uint64:        run< comma::uint64 >( options, to_type ); break;
//             case comma::csv::format::char_t:        run< char >( options, to_type ); break;
//             case comma::csv::format::float_t:       run< float >( options, to_type ); break;
//             case comma::csv::format::double_t:      run< double >( options, to_type ); break;
//             case comma::csv::format::time:
//             case comma::csv::format::long_time:     intervals< boost::posix_time::ptime >( options ).run(); break;
//             case comma::csv::format::fixed_string:  intervals< std::string >( options ).run(); break;
//             default:                                COMMA_THROW( comma::exception, "unknown type" ); break;
//         }
        if( from_type != to_type ) { std::cerr << app_name << ": support only from and to of the same type, got from: " << comma::csv::format::to_format( from_type ) << ", to: " << comma::csv::format::to_format( to_type ) << std::endl; return 1; }
        switch( to_type )
        {
            case comma::csv::format::int8:          intervals< char >( options ).run(); break;
            case comma::csv::format::uint8:         intervals< unsigned char >( options ).run(); break;
            case comma::csv::format::int16:         intervals< comma::int16 >( options ).run(); break;
            case comma::csv::format::uint16:        intervals< comma::uint16 >( options ).run(); break;
            case comma::csv::format::int32:         intervals< comma::int32 >( options ).run(); break;
            case comma::csv::format::uint32:        intervals< comma::uint32 >( options ).run(); break;
            case comma::csv::format::int64:         intervals< comma::int64 >( options ).run(); break;
            case comma::csv::format::uint64:        intervals< comma::uint64 >( options ).run(); break;
            case comma::csv::format::char_t:        intervals< char >( options ).run(); break;
            case comma::csv::format::float_t:       intervals< float >( options ).run(); break;
            case comma::csv::format::double_t:      intervals< double >( options ).run(); break;
            case comma::csv::format::time:
            case comma::csv::format::long_time:     intervals< boost::posix_time::ptime >( options ).run(); break;
            case comma::csv::format::fixed_string:  intervals< std::string >( options ).run(); break;            
            default:                                COMMA_THROW( comma::exception, "from/to type mismatch" ); break;
        }
        return 0;
    }
    catch( std::exception& ex ) { std::cerr << app_name << ": " << ex.what() << std::endl; }
    catch( ... ) { std::cerr << app_name << ": unknown exception" << std::endl; }
    return 1;
}
Example #20
0
FEELPP_EXPORT
void ginacBuildLibrary( GiNaC::lst const& exprs, GiNaC::lst const& syml, std::string const& exprDesc, std::string const& filename, WorldComm const& world,
                        std::shared_ptr<GiNaC::FUNCP_CUBA>& cfun )
{
    // register the GinacExprManager into Feel::Environment so that it gets the
    // GinacExprManager is cleared up when the Environment is deleted
    static bool observed = false;
    if ( !observed )
    {
        Environment::addDeleteObserver( GinacExprManagerDefaultFileNameDeleter::instance() );
        Environment::addDeleteObserver( GinacExprManagerDeleter::instance() );
        observed = true;
    }

    std::string keyExprManager = exprDesc;
    if ( exprDesc.empty() && !filename.empty() )
        keyExprManager = filename;

    bool hasLinked = ( GinacExprManager::instance().find( keyExprManager /*exprDesc*/ /*filename*/ ) != GinacExprManager::instance().end() ) ? true : false;
    if ( hasLinked )
    {
        cfun = GinacExprManager::instance().find( keyExprManager /*exprDesc*/ /*filename*/ )->second;
    }
    else
    {
        std::string filenameDescExpr = filename + ".desc";
        std::string filenameWithSuffix =  filename + ".so";
        if ( !fs::path(filename).is_absolute() )
        {
            filenameDescExpr = Environment::exprRepository() + filename + ".desc";
            filenameWithSuffix =  Environment::exprRepository() + filename + ".so";
        }

        bool doRebuildGinacLib = true;
        // load .desc file and compare if both expr are identical
        if ( world.isMasterRank() && !filename.empty() && fs::exists( filenameDescExpr ) && fs::exists( filenameWithSuffix ) )
        {
            std::string exprInFile;
            std::ifstream file( filenameDescExpr, std::ios::in );
            std::getline( file, exprInFile );
            file.close();
            // if equal else not rebuild ginac
            if ( exprInFile == exprDesc )
                doRebuildGinacLib = false;
        }

        // master rank check if the lib exist and compile this one if not done
        if ( ( world.isMasterRank() && doRebuildGinacLib ) || filename.empty() )
        {
            if ( !filename.empty() && fs::path( filename ).is_absolute() )
            {
                if ( !fs::exists( fs::path( filename ).parent_path() ) )
                    fs::create_directories( fs::path( filename ).parent_path() );
                DVLOG( 2 ) << "GiNaC::compile_ex with filenameWithSuffix " << filenameWithSuffix << "\n";
                GiNaC::compile_ex( exprs, syml, *cfun, filename );
            }
            else if ( !filename.empty() )
            {
                DVLOG( 2 ) << "GiNaC::compile_ex with filenameWithSuffix " << filenameWithSuffix << "\n";
                GiNaC::compile_ex( exprs, syml, *cfun, Environment::exprRepository() + "/" + filename );
            }
            else
            {
                DVLOG( 2 ) << "GiNaC::compile_ex with filenameWithSuffix " << filenameWithSuffix << "\n";
                GiNaC::compile_ex( exprs, syml, *cfun, filename );
            }
                     

            hasLinked = true;
            if ( !filename.empty() )
            {
                GinacExprManager::instance().operator[]( keyExprManager /*exprDesc*/ /*filename*/ ) = cfun;

                if ( !exprDesc.empty() )
                {
                    std::ofstream file( filenameDescExpr, std::ios::out | std::ios::trunc );
                    file << exprDesc;
                    file.close();
                }
            }
        }
        // wait the lib compilation
        if ( !filename.empty() )
            world.barrier();
        // link with other process
        if ( !hasLinked )
        {
            DVLOG( 2 ) << "GiNaC::link_ex with filenameWithSuffix " << filenameWithSuffix << "\n";
            GiNaC::link_ex( filenameWithSuffix, *cfun );
            if ( !filename.empty() )
                GinacExprManager::instance().operator[]( keyExprManager /*exprDesc*/ /*filename*/ ) = cfun;
        }
    }
}
Example #21
0
bool p2p::isLocalHostAddress(std::string const& _addressToCheck)
{
    return _addressToCheck.empty() ? false : isLocalHostAddress(bi::address::from_string(_addressToCheck));
}
Example #22
0
/// \brief When the source code line we want to print is too long for
/// the terminal, select the "interesting" region.
static void selectInterestingSourceRegion(std::string &SourceLine,
                                          std::string &CaretLine,
                                          std::string &FixItInsertionLine,
                                          unsigned Columns,
                                          const SourceColumnMap &map) {
  unsigned MaxColumns = std::max<unsigned>(map.columns(),
                                           std::max(CaretLine.size(),
                                                    FixItInsertionLine.size()));
  // if the number of columns is less than the desired number we're done
  if (MaxColumns <= Columns)
    return;

  // No special characters are allowed in CaretLine.
  assert(CaretLine.end() ==
         std::find_if(CaretLine.begin(), CaretLine.end(),
                      [](char c) { return c < ' ' || '~' < c; }));

  // Find the slice that we need to display the full caret line
  // correctly.
  unsigned CaretStart = 0, CaretEnd = CaretLine.size();
  for (; CaretStart != CaretEnd; ++CaretStart)
    if (!isWhitespace(CaretLine[CaretStart]))
      break;

  for (; CaretEnd != CaretStart; --CaretEnd)
    if (!isWhitespace(CaretLine[CaretEnd - 1]))
      break;

  // caret has already been inserted into CaretLine so the above whitespace
  // check is guaranteed to include the caret

  // If we have a fix-it line, make sure the slice includes all of the
  // fix-it information.
  if (!FixItInsertionLine.empty()) {
    unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
    for (; FixItStart != FixItEnd; ++FixItStart)
      if (!isWhitespace(FixItInsertionLine[FixItStart]))
        break;

    for (; FixItEnd != FixItStart; --FixItEnd)
      if (!isWhitespace(FixItInsertionLine[FixItEnd - 1]))
        break;

    // We can safely use the byte offset FixItStart as the column offset
    // because the characters up until FixItStart are all ASCII whitespace
    // characters.
    unsigned FixItStartCol = FixItStart;
    unsigned FixItEndCol
      = llvm::sys::locale::columnWidth(FixItInsertionLine.substr(0, FixItEnd));

    CaretStart = std::min(FixItStartCol, CaretStart);
    CaretEnd = std::max(FixItEndCol, CaretEnd);
  }

  // CaretEnd may have been set at the middle of a character
  // If it's not at a character's first column then advance it past the current
  //   character.
  while (static_cast<int>(CaretEnd) < map.columns() &&
         -1 == map.columnToByte(CaretEnd))
    ++CaretEnd;

  assert((static_cast<int>(CaretStart) > map.columns() ||
          -1!=map.columnToByte(CaretStart)) &&
         "CaretStart must not point to a column in the middle of a source"
         " line character");
  assert((static_cast<int>(CaretEnd) > map.columns() ||
          -1!=map.columnToByte(CaretEnd)) &&
         "CaretEnd must not point to a column in the middle of a source line"
         " character");

  // CaretLine[CaretStart, CaretEnd) contains all of the interesting
  // parts of the caret line. While this slice is smaller than the
  // number of columns we have, try to grow the slice to encompass
  // more context.

  unsigned SourceStart = map.columnToByte(std::min<unsigned>(CaretStart,
                                                             map.columns()));
  unsigned SourceEnd = map.columnToByte(std::min<unsigned>(CaretEnd,
                                                           map.columns()));

  unsigned CaretColumnsOutsideSource = CaretEnd-CaretStart
    - (map.byteToColumn(SourceEnd)-map.byteToColumn(SourceStart));

  char const *front_ellipse = "  ...";
  char const *front_space   = "     ";
  char const *back_ellipse = "...";
  unsigned ellipses_space = strlen(front_ellipse) + strlen(back_ellipse);

  unsigned TargetColumns = Columns;
  // Give us extra room for the ellipses
  //  and any of the caret line that extends past the source
  if (TargetColumns > ellipses_space+CaretColumnsOutsideSource)
    TargetColumns -= ellipses_space+CaretColumnsOutsideSource;

  while (SourceStart>0 || SourceEnd<SourceLine.size()) {
    bool ExpandedRegion = false;

    if (SourceStart>0) {
      unsigned NewStart = map.startOfPreviousColumn(SourceStart);

      // Skip over any whitespace we see here; we're looking for
      // another bit of interesting text.
      // FIXME: Detect non-ASCII whitespace characters too.
      while (NewStart && isWhitespace(SourceLine[NewStart]))
        NewStart = map.startOfPreviousColumn(NewStart);

      // Skip over this bit of "interesting" text.
      while (NewStart) {
        unsigned Prev = map.startOfPreviousColumn(NewStart);
        if (isWhitespace(SourceLine[Prev]))
          break;
        NewStart = Prev;
      }

      assert(map.byteToColumn(NewStart) != -1);
      unsigned NewColumns = map.byteToColumn(SourceEnd) -
                              map.byteToColumn(NewStart);
      if (NewColumns <= TargetColumns) {
        SourceStart = NewStart;
        ExpandedRegion = true;
      }
    }

    if (SourceEnd<SourceLine.size()) {
      unsigned NewEnd = map.startOfNextColumn(SourceEnd);

      // Skip over any whitespace we see here; we're looking for
      // another bit of interesting text.
      // FIXME: Detect non-ASCII whitespace characters too.
      while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd]))
        NewEnd = map.startOfNextColumn(NewEnd);

      // Skip over this bit of "interesting" text.
      while (NewEnd < SourceLine.size() && isWhitespace(SourceLine[NewEnd]))
        NewEnd = map.startOfNextColumn(NewEnd);

      assert(map.byteToColumn(NewEnd) != -1);
      unsigned NewColumns = map.byteToColumn(NewEnd) -
                              map.byteToColumn(SourceStart);
      if (NewColumns <= TargetColumns) {
        SourceEnd = NewEnd;
        ExpandedRegion = true;
      }
    }

    if (!ExpandedRegion)
      break;
  }

  CaretStart = map.byteToColumn(SourceStart);
  CaretEnd = map.byteToColumn(SourceEnd) + CaretColumnsOutsideSource;

  // [CaretStart, CaretEnd) is the slice we want. Update the various
  // output lines to show only this slice, with two-space padding
  // before the lines so that it looks nicer.

  assert(CaretStart!=(unsigned)-1 && CaretEnd!=(unsigned)-1 &&
         SourceStart!=(unsigned)-1 && SourceEnd!=(unsigned)-1);
  assert(SourceStart <= SourceEnd);
  assert(CaretStart <= CaretEnd);

  unsigned BackColumnsRemoved
    = map.byteToColumn(SourceLine.size())-map.byteToColumn(SourceEnd);
  unsigned FrontColumnsRemoved = CaretStart;
  unsigned ColumnsKept = CaretEnd-CaretStart;

  // We checked up front that the line needed truncation
  assert(FrontColumnsRemoved+ColumnsKept+BackColumnsRemoved > Columns);

  // The line needs some trunctiona, and we'd prefer to keep the front
  //  if possible, so remove the back
  if (BackColumnsRemoved > strlen(back_ellipse))
    SourceLine.replace(SourceEnd, std::string::npos, back_ellipse);

  // If that's enough then we're done
  if (FrontColumnsRemoved+ColumnsKept <= Columns)
    return;

  // Otherwise remove the front as well
  if (FrontColumnsRemoved > strlen(front_ellipse)) {
    SourceLine.replace(0, SourceStart, front_ellipse);
    CaretLine.replace(0, CaretStart, front_space);
    if (!FixItInsertionLine.empty())
      FixItInsertionLine.replace(0, CaretStart, front_space);
  }
}
// virtual
BOOL LLPreviewGesture::handleDragAndDrop(S32 x, S32 y, MASK mask, BOOL drop,
										 EDragAndDropType cargo_type,
										 void* cargo_data,
										 EAcceptance* accept,
										 std::string& tooltip_msg)
{
	BOOL handled = TRUE;
	switch(cargo_type)
	{
	case DAD_ANIMATION:
	case DAD_SOUND:
		{
			// TODO: Don't allow this if you can't transfer the sound/animation

			// make a script step
			LLInventoryItem* item = (LLInventoryItem*)cargo_data;
			if (item
				&& gInventory.getItem(item->getUUID()))
			{
				LLPermissions perm = item->getPermissions();
				if (!((perm.getMaskBase() & PERM_ITEM_UNRESTRICTED) == PERM_ITEM_UNRESTRICTED))
				{
					*accept = ACCEPT_NO;
					if (tooltip_msg.empty())
					{
						tooltip_msg.assign("Only animations and sounds\n"
											"with unrestricted permissions\n"
											"can be added to a gesture.");
					}
					break;
				}
				else if (drop)
				{
					LLScrollListItem* line = NULL;
					if (cargo_type == DAD_ANIMATION)
					{
						line = addStep( STEP_ANIMATION );
						LLGestureStepAnimation* anim = (LLGestureStepAnimation*)line->getUserdata();
						anim->mAnimAssetID = item->getAssetUUID();
						anim->mAnimName = item->getName();
					}
					else if (cargo_type == DAD_SOUND)
					{
						line = addStep( STEP_SOUND );
						LLGestureStepSound* sound = (LLGestureStepSound*)line->getUserdata();
						sound->mSoundAssetID = item->getAssetUUID();
						sound->mSoundName = item->getName();
					}
					updateLabel(line);
					mDirty = TRUE;
					refresh();
				}
				*accept = ACCEPT_YES_COPY_MULTI;
			}
			else
			{
				// Not in user's inventory means it was in object inventory
				*accept = ACCEPT_NO;
			}
			break;
		}
	default:
		*accept = ACCEPT_NO;
		if (tooltip_msg.empty())
		{
			tooltip_msg.assign("Only animations and sounds\n"
								"can be added to a gesture.");
		}
		break;
	}
	return handled;
}
Example #24
0
void Text::init(RCPtr<Font> fnt, const std::string &str, bool use_kerning)
{
	assert(fnt.get());
	assert(! str.empty());

	mFont = fnt;

	mVerts.reset(new VertexBuffer((unsigned int)str.size() * 4, kFontVertexFormat, GL_STREAM_DRAW_ARB, false));

	VertexBufferLock lock(*mVerts);
	float *v = lock.get<float>();

	float x = 0.0f, y = 0.0f;

	mWidth = 0.0f;
	mHeight = 0.0f;

	mNumVerts = 0;
	char prev_char = 0;
	for (size_t i = 0; i < str.size(); ++i)
	{
		char c = str[i];

		if (c == '\r' || c == '\n')
		{
			++i;

			if (i < str.size() && str[i] == '\r' || str[i] == '\n')
				++i;
			
			if (i == str.size())
				break;

			// newline breaks up kerning pairs
			prev_char = 0;
			
			mWidth = std::max(mWidth, x);

			x = 0.0f;
			y += mFont->getLineHeight();

			continue;
		}

		// Get the normal character information
		const Font::CharInfo &ci = mFont->getCharInfo(c);

		// Get the kerning pair offset, if there is one
		float kerning_offset = 0.0f;

		if (use_kerning && (prev_char != 0))
			kerning_offset = mFont->getKerningOffset(prev_char, c);

		prev_char = c;

		x += kerning_offset;

		if (! ci.draw)
		{
			x += ci.advance;
			continue;
		}

		// Add the vertices

		// TopLeft
		*v++ = ci.texTopLeft[0]; // u
		*v++ = ci.texTopLeft[1]; // v
		*v++ = x + ci.posTopLeft[0]; // x
		*v++ = y + ci.posTopLeft[1]; // y

		// BottomLeft
		*v++ = ci.texTopLeft[0]; // u
		*v++ = ci.texBottomRight[1]; // v
		*v++ = x + ci.posTopLeft[0]; // x
		*v++ = y + ci.posBottomRight[1]; // y
		
		// BottomRight
		*v++ = ci.texBottomRight[0]; // u
		*v++ = ci.texBottomRight[1]; // v
		*v++ = x + ci.posBottomRight[0]; // x
		*v++ = y + ci.posBottomRight[1]; // y

		// TopRight
		*v++ = ci.texBottomRight[0]; // u
		*v++ = ci.texTopLeft[1]; // v
		*v++ = x + ci.posBottomRight[0]; // x
		*v++ = y + ci.posTopLeft[1]; // y

		x += ci.advance;

		mNumVerts += 4;
	}

	lock.reset();

	mWidth = std::max(x, mWidth);
	mHeight = y + mFont->getLineHeight();
}
Example #25
0
Path Path::appendExt(const std::string &ext) const
{
  if (ext.empty()) return Path(*this);
  else if (ext[0] == '.') return Path(data + ext);
  else return Path(data + "." + ext);
}
Example #26
0
void TlsOptions::setOption( tls_option opt, const std::string& value ) const {
    checkOpt(opt, STRING);
    this->setOption( opt, value.empty() ? NULL : (void*) value.c_str() );
}
Example #27
0
 bool ParseFloat(const std::string& string, float& value)
 {
   return swri_string_util::ToFloat(string, value) || string.empty();
 }
Example #28
0
void Browser::getDirectory(std::string directory)
{
	m_scroll_beginning = 0;
	w.clear();

	// reset the position if we change directories
	if (m_current_directory != directory)
		w.reset();

	// check if it's a parent directory
	if (isStringParentDirectory(directory))
	{
		directory.resize(directory.length()-3);
		directory = getParentDirectory(directory);
	}
	// when we go down to root, it can be empty
	if (directory.empty())
		directory = "/";

	std::vector<MPD::Item> items;
	if (m_local_browser)
		getLocalDirectory(items, directory);
	else
	{
		std::copy(
			std::make_move_iterator(Mpd.GetDirectory(directory)),
			std::make_move_iterator(MPD::ItemIterator()),
			std::back_inserter(items)
		);
	}

	// sort items
	if (Config.browser_sort_mode != SortMode::NoOp)
	{
		std::sort(items.begin(), items.end(),
			LocaleBasedItemSorting(std::locale(), Config.ignore_leading_the, Config.browser_sort_mode)
		);
	}

	// if the requested directory is not root, add parent directory
	if (!isRootDirectory(directory))
	{
		// make it so that display function doesn't have to handle special cases
		w.addItem(MPD::Directory(directory + "/.."), NC::List::Properties::None);
	}

	for (const auto &item : items)
	{
		switch (item.type())
		{
			case MPD::Item::Type::Playlist:
			{
				w.addItem(std::move(item));
				break;
			}
			case MPD::Item::Type::Directory:
			{
				bool is_current = item.directory().path() == m_current_directory;
				w.addItem(std::move(item));
				if (is_current)
					w.highlight(w.size()-1);
				break;
			}
			case MPD::Item::Type::Song:
			{
				auto properties = NC::List::Properties::Selectable;
				if (myPlaylist->checkForSong(item.song()))
					properties |= NC::List::Properties::Bold;
				w.addItem(std::move(item), properties);
				break;
			}
		}
	}
	m_current_directory = directory;
}
Example #29
0
// Main entry point
int main (int argc, char** argv)
{
  std::string pathToThisFile=__FILE__;

  if(gDataPath.empty())
    gDataPath=rt::Math::getParentDirectoryFromFilePath(pathToThisFile);
  std::cerr<<"Using data path: "<<gDataPath<<std::endl;

  std::cerr<<"Use your mouse to rotate,pan and zoom the camera"<<std::endl;
  std::cerr<<"left mouse button + drag -> rotate"<<std::endl;
  std::cerr<<"middle mouse button + drag -> pan"<<std::endl;
  std::cerr<<"scroll wheel up / down -> zoom in / out"<<std::endl;

  if( !glfwInit() )
  {
    std::cerr<<"Failed to initialize GLFW\n"<<std::endl;
    return -1;
  }

  glfwSetErrorCallback(glfwErrorCallback);

  // Create the OpenGL window
  glfwWindowHint(GLFW_DEPTH_BITS, 16);
  glfwWindowHint(GLFW_SAMPLES, 4);

  //Those stop GLFW from initializing successfully?
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
  glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

  // Open OpenGL fullscreen window
  gGLFWWindow = glfwCreateWindow(gWidth,gHeight,"GLFW OpenGL Window",nullptr,nullptr);

  //// Open OpenGL fullscreen window
  //if( !glfwOpenWindow( gWidth, gHeight, 0,0,0,0, 16,0, GLFW_WINDOW ) )
  //{
  //  fprintf( stderr, "Failed to open GLFW window\n" );
  //  glfwTerminate();
  //  exit( EXIT_FAILURE );
  //}

  if(!gGLFWWindow)
  {
    std::cerr<<"Failed to open GLFW window\n"<<std::endl;
    glfwTerminate();
    return -1;
  }

  // Disable VSync (we want to get as high FPS as possible!)

  glfwMakeContextCurrent(gGLFWWindow);
  glfwSwapInterval( 1 );

  // Setting this is necessary for core profile (tested with MSVC 2013 x64, Windows 7)
  glewExperimental = GL_TRUE;
  // GLEW wraps all OpenGL functions and extensions
  GLenum err = glewInit();
  if(err != GLEW_OK)
  {
    std::cerr<<"Failed to initialize GLEW"<<std::endl;
    std::cerr<<(char*)glewGetErrorString(err)<<std::endl;
    glfwTerminate();
    return -1;
  }
  glGetError(); //GLEW might cause an 'invalid enum' error, safely ignore it?

  // Print OpenGL context information to console
  ogl::printContextInformation();

  // Perform our initialization (OpenGL states, shader, camera, geometry)
  if(!init())
    return -1;

  // Set the appropriate callback functions
  // Window resize callback function
  glfwSetFramebufferSizeCallback(gGLFWWindow,resizeCB);
  glfwSetMouseButtonCallback(gGLFWWindow,mouseCB);
  glfwSetScrollCallback(gGLFWWindow,wheelCB);
  glfwSetCursorPosCallback(gGLFWWindow,motionCB);


  while( !glfwWindowShouldClose(gGLFWWindow) )
  {
    // Get the current time (in milliseconds since program start)
    double t0 =glfwGetTime();

    // Clear frame and depth buffers
    glClearColor(gBackgroundColor[0],gBackgroundColor[1],gBackgroundColor[2], 1.f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // Draw...
    displayCB();

    // Hopefully there hasn't been any mistake?
    ogl::printOpenGLError();

    // Swap the rendering target with the frame buffer shown on the monitor
    glfwSwapBuffers(gGLFWWindow);

    glfwPollEvents() ;

    // Compute rendering time in seconds by taking difference to current time
    double t1=glfwGetTime();
    gLastFrameTime = float(t1-t0);
  }

  // Terminate OpenGL
  glfwTerminate();
  return 0;
}
Example #30
0
void ConfigManager::getChildren(std::string path,
        std::vector<std::string> & destList)
{
    if(path.empty())
    {
        return;
    }

    for(int i = 0; i < _configRootList.size(); i++)
    {
        std::string pathFrag;
        std::string pathRemainder = path;
        mxml_node_t * xmlNode = _configRootList[i]->child;

        size_t location = pathRemainder.find_first_of('.');
        if(location == std::string::npos)
        {
            pathFrag = pathRemainder;
            pathRemainder = "";
        }
        else
        {
            pathFrag = pathRemainder.substr(0,location);
            if(location + 1 < pathRemainder.size())
            {
                pathRemainder = pathRemainder.substr(location + 1);
            }
            else
            {
                pathRemainder = "";
            }
        }

        std::stack<std::pair<mxml_node_t *,std::string> > parentStack;

        do
        {
            if(!parentStack.empty())
            {
                xmlNode = parentStack.top().first->next;
                if(!pathRemainder.empty())
                {
                    pathRemainder = pathFrag + "." + pathRemainder;
                }
                else
                {
                    pathRemainder = pathFrag;
                }
                pathFrag = parentStack.top().second;
                parentStack.pop();
            }
            while(xmlNode)
            {
                if(xmlNode->type != MXML_ELEMENT)
                {
                    xmlNode = xmlNode->next;
                    continue;
                }
                std::string nodeName = xmlNode->value.element.name;
                const char * nameAtt = mxmlElementGetAttr(xmlNode,"name");
                std::string suffix = nameAtt ? nameAtt : "";

                //std::cerr << "Looking at node: " << nodeName << " with suffix " << suffix << std::endl;

                location = pathFrag.find_first_of(':');
                if((location == std::string::npos && pathFrag == nodeName)
                        || (location != std::string::npos
                                && pathFrag == nodeName + ":" + suffix))
                {
                    //std::cerr << "Found Fragment." << std::endl;
                    if(pathRemainder.empty())
                    {
                        if(xmlNode->child)
                        {
                            mxml_node_t * cnode = xmlNode->child;
                            while(cnode)
                            {
                                if(cnode->type != MXML_ELEMENT)
                                {
                                    cnode = cnode->next;
                                    continue;
                                }
                                // ignore comment tags
                                if(strncmp(cnode->value.element.name,"!--",3))
                                {
                                    destList.push_back(
                                            cnode->value.element.name);
                                }
                                cnode = cnode->next;
                            }
                        }
                        xmlNode = xmlNode->next;
                    }
                    else
                    {
                        parentStack.push(
                                std::pair<mxml_node_t *,std::string>(xmlNode,
                                        pathFrag));
                        location = pathRemainder.find_first_of('.');
                        if(location == std::string::npos)
                        {
                            pathFrag = pathRemainder;
                            pathRemainder = "";
                        }
                        else
                        {
                            pathFrag = pathRemainder.substr(0,location);
                            if(location + 1 < pathRemainder.size())
                            {
                                pathRemainder = pathRemainder.substr(
                                        location + 1);
                            }
                            else
                            {
                                pathRemainder = "";
                            }
                        }
                        //std::cerr << "Looking for fragment: " << pathFrag << std::endl;
                        //std::cerr << "with remainder: " << pathRemainder << std::endl;
                        xmlNode = xmlNode->child;
                    }
                }
                else
                {
                    xmlNode = xmlNode->next;
                }
            }
        }
        while(!parentStack.empty());
    }
    return;
}