Example #1
0
bool DBConnector::checkIfGpsDataExsist(const String& timedate, int user)
{
	bool result = false;
	try{
		{
			String query;
			query << "SELECT time FROM gpsdata WHERE time = '" << timedate << "' AND user = "******";";
			sqlite3_command cmd(*m_dbconn, std::string(query.toUTF8().getAddress()));
			sqlite3_reader reader = cmd.executereader();
			while (reader.read()) {
				result = true;
				break;
			}
		}
	}
	CATCHDBERRORS
	return result;
}
Example #2
0
bool DBConnector::insertUser(int userid, const String& username)
{
	bool result = false;
	try {
		sqlite3_transaction trans(*m_dbconn);
		{
			String query = String::empty;
			query << "INSERT INTO user (userid, name) VALUES (" << userid << ",'" << username << "');";
			sqlite3_command cmd(*m_dbconn, std::string(query.toUTF8().getAddress()));
			cmd.executenonquery();
		}
		trans.commit();
		result = true;
	}
	CATCHDBERRORS
    return result;

}
Example #3
0
		PixelShader_GL(const String& source)
		{
			const std::string sourceUTF8 = source.toUTF8();
			
			const char* pSource = sourceUTF8.c_str();
			
			m_psProgram = ::glCreateShaderProgramv(GL_FRAGMENT_SHADER, 1, &pSource);
			
			GLint status = GL_FALSE;
			
			::glGetProgramiv(m_psProgram, GL_LINK_STATUS, &status);
			
			GLint logLen = 0;
			
			::glGetProgramiv(m_psProgram, GL_INFO_LOG_LENGTH, &logLen);
			
			if (logLen > 4)
			{
				std::string log(logLen + 1, '\0');
				
				::glGetProgramInfoLog(m_psProgram, logLen, &logLen, &log[0]);
				
				LOG_FAIL(U"❌ Pixel shader compilation failed: {0}"_fmt(Unicode::Widen(log)));
			}
			
			if (status == GL_FALSE)
			{
				::glDeleteProgram(m_psProgram);
				
				m_psProgram = 0;
			}
			
			if (m_psProgram)
			{
				const int32 t = ::glGetUniformLocation(m_psProgram, "Tex0");
				
				if (t != -1)
				{
					m_textureIndex = t;
				}
			}
			
			m_initialized = m_psProgram != 0;
		}
Example #4
0
    void buttonClicked (Button* button)
    {
        if (button == &sendButton)
        {
            // The send button has been pressed, so write out the contents of the
            // text box to the socket or pipe, depending on which is active.
            const String text (sendText.getText());
            MemoryBlock messageData (text.toUTF8(), text.getNumBytesAsUTF8());

            for (int i = activeConnections.size(); --i >= 0;)
            {
                if (! activeConnections[i]->sendMessage (messageData))
                {
                    // the write failed, so indicate that the connection has broken..
                    appendMessage ("send message failed!");
                }
            }
        }
    }
bool Utils::writeStringToFile(const String& s, const File& f)
{
	TemporaryFile temp (f);

	ScopedPointer <FileOutputStream> out (temp.getFile().createOutputStream());

	if (out != nullptr)
	{
		out->write(s.toUTF8(), s.getNumBytesAsUTF8());
		out = nullptr; // (deletes the stream)

		bool succeeded = temp.overwriteTargetFileWithTemporary();
		return succeeded;
	}
	else
	{
		return false;
	}
}
Example #6
0
const MLSymbol MLPluginProcessor::XMLAttrToSymbol(const String& str)
{
	std::string strCopy(str.toUTF8());
	
	unsigned len = strCopy.length();
	for(unsigned c = 0; c < len; ++c)
	{
		unsigned char k = strCopy[c];
		if(k == ':')
		{
			strCopy[c] = '#';
		}
		else if(k == 0xB7)
		{
			strCopy[c] = '*';
		}
	}
 	return (MLSymbol(strCopy.c_str()));
}
Example #7
0
void RecordNode::openFile(Channel* ch)
{
    std::cout << "OPENING FILE: " << ch->filename << std::endl;

    File f = File(ch->filename);
    FILE* chFile;

    bool fileExists = f.exists();
    
    diskWriteLock.enter();

    chFile = fopen(ch->filename.toUTF8(), "ab");

    if (!fileExists)
    {
        // create and write header
        std::cout << "Writing header." << std::endl;
        String header = generateHeader(ch);
        //std::cout << header << std::endl;
        std::cout << "File ID: " << chFile << ", number of bytes: " << header.getNumBytesAsUTF8() << std::endl;


        fwrite(header.toUTF8(), 1, header.getNumBytesAsUTF8(), chFile);

        std::cout << "Wrote header." << std::endl;

        std::cout << "Block index: " << blockIndex << std::endl;

    }
    else
    {
        std::cout << "File already exists, just opening." << std::endl;
    }

    diskWriteLock.exit();

    //To avoid a race condition resulting on data written before the header,
    //do not assign the channel pointer until the header has been written
    ch->file = chFile;


}
Example #8
0
bool Process::openDocument (const String& fileName, const String& parameters)
{
    String cmdString (fileName.replace (" ", "\\ ",false));
    cmdString << " " << parameters;

    if (/*URL::isProbablyAWebsiteURL (fileName)
          ||*/ cmdString.startsWithIgnoreCase ("file:")
         /*|| URL::isProbablyAnEmailAddress (fileName)*/
         || File::createFileWithoutCheckingPath (fileName).isDirectory()
         || ! isFileExecutable (fileName))
    {
        // create a command that tries to launch a bunch of likely browsers
        static const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla",
                                                    "google-chrome", "chromium-browser", "opera", "konqueror" };
        StringArray cmdLines;

        for (int i = 0; i < numElementsInArray (browserNames); ++i)
            cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());

        cmdString = cmdLines.joinIntoString (" || ");
    }

    const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), nullptr };

#if JUCE_USE_VFORK
    const int cpid = vfork();
#else
    const int cpid = fork();
#endif

    if (cpid == 0)
    {
#if ! JUCE_USE_VFORK
        setsid();
#endif
        // Child process
        if (execvp (argv[0], (char**) argv) < 0)
            _exit (0);
    }

    return cpid >= 0;
}
Example #9
0
bool DBConnector::getGpsLocations(Array<GpsLocation>& locations)
{
	bool result = false;
	try{
		sqlite3_transaction trans(*m_dbconn);
		{
			String query;
			query << "select * from location;";
			sqlite3_command cmd(*m_dbconn, std::string(query.toUTF8().getAddress()));
			sqlite3_reader reader = cmd.executereader();
			locations.clear();
			while (reader.read()) {
				GpsLocation location;
				location.index = reader.getint(0);
				location.city = String(CharPointer_UTF8(reader.getstring(1).data()));
//                DBG(location.city);
				location.country = String(CharPointer_UTF8(reader.getstring(2).data()));
				location.longitude = reader.getdouble(3);
				location.latitude = reader.getdouble(4);
				location.radius = reader.getdouble(5);
				location.radiusKm = reader.getdouble(6);
				String polygonStr(CharPointer_UTF8(reader.getstring(7).data()));
				Helper::getPointsFromPolygonString(polygonStr, location.polygon);
				location.bottomLeft.setX(reader.getdouble(8));
				location.bottomLeft.setY(reader.getdouble(9));
				location.topRight.setX(reader.getdouble(10));
				location.topRight.setY(reader.getdouble(11));
				locations.add(location);
//				DBG_VAL(location.index);
//				DBG_VAL(location.city);
//				DBG_VAL(location.country);
//				DBG_VAL(location.longitude );
//				DBG_VAL(location.latitude);
//				DBG_VAL(location.radius);
			}
		}
		trans.commit();
		result = true;
	}
	CATCHDBERRORS
	return result;
}
void SerialOscController::sendDevicePrefixMessage(int port)
{
	String prefix = devicePrefix;

	if (prefix.startsWith("/")) {
		prefix = prefix.substring(1);
	}

	UdpTransmitSocket transmitSocket( IpEndpointName( SERIALOSC_ADDRESS, port ) );
    char buffer[OSC_BUFFER_SIZE];
    osc::OutboundPacketStream p( buffer, OSC_BUFFER_SIZE );
    
    p << osc::BeginBundleImmediate
        << osc::BeginMessage( "/sys/prefix" )
			<< prefix.toUTF8()
            << osc::EndMessage
        << osc::EndBundle;
    
    transmitSocket.Send( p.Data(), p.Size() );
}
Example #11
0
bool DBConnector::checkIfCityExists(const String& cityname)
{
	bool result = false;
	try{
		sqlite3_transaction trans(*m_dbconn);
		{
			String query;
			query << "select city from location where city = '" << cityname << "';";
			sqlite3_command cmd(*m_dbconn, std::string(query.toUTF8().getAddress()));
			sqlite3_reader reader = cmd.executereader();
			while (reader.read()) {
				result = true;
				break;
			}
		}
		trans.commit();
	}
	CATCHDBERRORS
	return result;
}
Example #12
0
    static bool bindSocket (const SocketHandle handle, const int port, const String& address) noexcept
    {
        if (handle <= 0 || port < 0)
            return false;

        struct sockaddr_in servTmpAddr;
        zerostruct (servTmpAddr); // (can't use "= { 0 }" on this object because it's typedef'ed as a C struct)
        servTmpAddr.sin_family = PF_INET;
        servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
        servTmpAddr.sin_port = htons ((uint16) port);

       #if JUCE_WINDOWS
        if (address.isNotEmpty())
            servTmpAddr.sin_addr.s_addr = ::inet_addr (address.toUTF8());
       #else
        ignoreUnused (address);
       #endif

        return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
    }
Example #13
0
 int doFTime (CharPointer_UTF32 dest, const size_t maxChars, const String& format, const struct tm* const tm) noexcept
 {
    #if JUCE_ANDROID
     HeapBlock <char> tempDest;
     tempDest.calloc (maxChars + 2);
     const int result = (int) strftime (tempDest, maxChars, format.toUTF8(), tm);
     if (result > 0)
         dest.writeAll (CharPointer_UTF8 (tempDest.getData()));
     return result;
    #elif JUCE_WINDOWS
     HeapBlock <wchar_t> tempDest;
     tempDest.calloc (maxChars + 2);
     const int result = (int) wcsftime (tempDest, maxChars, format.toWideCharPointer(), tm);
     if (result > 0)
         dest.writeAll (CharPointer_UTF16 (tempDest.getData()));
     return result;
    #else
     return (int) wcsftime (dest.getAddress(), maxChars, format.toUTF32(), tm);
    #endif
 }
Example #14
0
bool DBConnector::getLastId(int& lastRowId, const String& tableName)
{
	bool result = false;
	lastRowId = -1;
	try {
		sqlite3_transaction trans(*m_dbconn);
		{
			String query;
			query << "Select seq from sqlite_sequence where name = '" << tableName << "';";
			sqlite3_command cmd(*m_dbconn, std::string(query.toUTF8().getAddress()));
			//sqlite3_reader reader = cmd.executereader();
			//lastRowId = reader.getint(0);
			lastRowId = cmd.executeint();
		}
		trans.commit();
		result = true;
	}
	CATCHDBERRORS
	return result;
}
Example #15
0
//==============================================================================
bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
{
    if (connected)
        close();

    hostName = "listener";
    portNumber = newPortNumber;
    isListener = true;

    struct sockaddr_in servTmpAddr;
    zerostruct (servTmpAddr);

    servTmpAddr.sin_family = PF_INET;
    servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);

	if (localHostName.isNotEmpty())
	{
		inet_pton(PF_INET, localHostName.toUTF8(), &servTmpAddr.sin_addr);
		//servTmpAddr.sin_addr.s_addr = ::inet_addr(localHostName.toUTF8());
	}

    servTmpAddr.sin_port = htons ((uint16) portNumber);

    handle = (int) socket (AF_INET, SOCK_STREAM, 0);

    if (handle < 0)
        return false;

    const int reuse = 1;
    setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));

    if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
         || listen (handle, SOMAXCONN) < 0)
    {
        close();
        return false;
    }

    connected = true;
    return true;
}
Example #16
0
bool DBConnector::getTableNames(StringArray& names)
{
	bool res = false;
	String queryStr = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;";

	try {
		sqlite3_command cmd(*m_dbconn, queryStr.toUTF8().getAddress());
		sqlite3_reader reader=cmd.executereader();

		while(reader.read())
		{
			String tableName = reader.getstring(0).c_str();
			if(! tableName.contains("sqlite_"))
			{
				names.add(tableName);
			}
		}
	}
	CATCHDBERRORS
	return res;
}
Example #17
0
	TOMLValue TOMLValue::operator [](const String& path) const
	{
		if (isEmpty())
		{
			return TOMLValue();
		}

		if (auto&& table = m_detail->ptr->as_table())
		{
			try
			{
				return TOMLValue(detail::TOMLValueDetail(table->get_qualified(path.toUTF8())));
			}
			catch (...)
			{
				return TOMLValue();
			}
		}

		return TOMLValue();
	}
Example #18
0
bool DBConnector::checkIfFileExists(const String& md5hash)
{
	bool result = false;
	try{
		sqlite3_transaction trans(*m_dbconn);
		{
			String query;
			query << "select fileid from file where md5hash = '" << md5hash << "';";
			sqlite3_command cmd(*m_dbconn, std::string(query.toUTF8().getAddress()));
			sqlite3_reader reader = cmd.executereader();
			while (reader.read()) {
				result = true;
				break;
			}
		}
		trans.commit();
	}
	CATCHDBERRORS
	return result;

}
Example #19
0
bool DBConnector::getAvailableUsers(Array<String>& users)
{
	bool result = false;
	users.clear();
	try {
		sqlite3_transaction trans(*m_dbconn);
		{
			String query = "Select name from user;";
			sqlite3_command cmd(*m_dbconn, std::string(query.toUTF8().getAddress()));
			sqlite3_reader reader = cmd.executereader();
			while (reader.read()) {
				users.add(String((reader.getstring(0)).c_str()));
			}
		}
		trans.commit();
		result = true;
	}
	CATCHDBERRORS
	return result;

}
Example #20
0
//==============================================================================
bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
{
    if (connected)
        close();

    hostName = "listener";
    portNumber = newPortNumber;
    isListener = true;

    struct sockaddr_in servTmpAddr;
    zerostruct (servTmpAddr);

    servTmpAddr.sin_family = PF_INET;
    servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);

    if (localHostName.isNotEmpty())
        servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());

    servTmpAddr.sin_port = htons ((uint16) portNumber);

    handle = (int) socket (AF_INET, SOCK_STREAM, 0);

    if (handle < 0)
        return false;

   #if ! JUCE_WINDOWS // on windows, adding this option produces behaviour different to posix
    SocketHelpers::makeReusable (handle);
   #endif

    if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
         || listen (handle, SOMAXCONN) < 0)
    {
        close();
        return false;
    }

    connected = true;
    return true;
}
String EncryptedString::encrypt (const String& stringToEncrypt, const String& publicKey, bool resultAsHex)
{
    RSAKey rsaKey (publicKey);
    
    CharPointer_UTF8 stringPointer (stringToEncrypt.toUTF8());
    MemoryBlock stringMemoryBlock (stringPointer.getAddress(), stringPointer.sizeInBytes());

    BigInteger stringAsData;
    stringAsData.loadFromMemoryBlock (stringMemoryBlock);

    rsaKey.applyToValue (stringAsData);
    
    if (resultAsHex)
    {
        MemoryBlock encryptedMemoryBlock (stringAsData.toMemoryBlock());
        return String::toHexString ((char*) encryptedMemoryBlock.getData(), (int) encryptedMemoryBlock.getSize(), 0);
    }
    else
    {
        return stringAsData.toMemoryBlock().toBase64Encoding();
    }
}
Example #22
0
bool DBConnector::insertInitLocationDataGML()
{
    bool result = false;

    String gmlFile = CharPointer_UTF8(BinaryData::citydefs_gml);
    Array<GpsLocation> locs = GMLUtils::parse(gmlFile);

    Array<String> tmpLocations;
    String tmpStr = "";
    tmpLocations.add("1,'Unknown','Unknown','0.0,0.0 0.0,0.0 0.0,0.0 0.0,0.0 0.0,0.0'");
    for (int i = 0; i < locs.size(); ++i) {
    	tmpStr << locs[i].index+1 << ",\"" << locs[i].city << "\",";
    	tmpStr << "\"" << locs[i].country << "\",\"";
    	tmpStr << Helper::getPolygonStringFromPoints(locs[i].polygon);
    	tmpStr << "\"";
    	tmpLocations.add(tmpStr);
    	tmpStr = "";
    }
    try{
        sqlite3_transaction trans(*m_dbconn);
        {

            for (unsigned int i = 0; i < tmpLocations.size(); ++i) {
                String query = "INSERT INTO 'location' ";
                query << "(locationid,city,country,polygon)VALUES(";
                query << tmpLocations[i];
                query << ");";
                sqlite3_command cmd(*m_dbconn, std::string(query.toUTF8().getAddress()));
                cmd.executenonquery();
            }

        }
        trans.commit();
        result = true;
    }
    CATCHDBERRORS
    return result;

}
Example #23
0
bool DBConnector::insertInitLocationData()
{
    bool result = false;
    String locationsStr((CharPointer_UTF8(BinaryData::locations_csv)));
    Array<String> tmpLocations;
    String tmpStr = "";
    for (int i = 0; i < locationsStr.length(); ++i) {
        if (locationsStr[i] != '\n')
        {
            tmpStr << locationsStr[i];
        }
        else
        {
            tmpLocations.add(tmpStr);
            tmpStr = "";
        }
    }
    try{
        sqlite3_transaction trans(*m_dbconn);
        {

            for (unsigned int i = 1; i < tmpLocations.size(); ++i) {
                String query = "INSERT INTO 'location' ";
                query << "(locationid,city,country,longitude,latitude,radius)VALUES(";
                query << tmpLocations[i];
                query << ");";
                sqlite3_command cmd(*m_dbconn, std::string(query.toUTF8().getAddress()));
                cmd.executenonquery();
            }

        }
        trans.commit();
        result = true;
    }
    CATCHDBERRORS
    return result;

}
void SerialOscController::sendDeviceLedCommand(int x, int y, bool state)
{
	HashMap<String, MonomeDevice*>::Iterator iter(devices);

	while (iter.next()) {
		auto device = iter.getValue();

		UdpTransmitSocket transmitSocket( IpEndpointName( SERIALOSC_ADDRESS, device->port ) );
		char buffer[OSC_BUFFER_SIZE];
		osc::OutboundPacketStream p( buffer, OSC_BUFFER_SIZE );
		String address = (device->prefix + "/grid/led/set");

		p << osc::BeginBundleImmediate
			<< osc::BeginMessage( address.toUTF8() )
				<< x
				<< y
				<< (state ? 1 : 0)
				<< osc::EndMessage
			<< osc::EndBundle;
    
		transmitSocket.Send( p.Data(), p.Size() );
	}
}
Example #25
0
bool DBConnector::updateGpsDataLocation(int gpsdataid, int location)
{
    bool result = false;

    try
    {
        sqlite3_transaction trans(*m_dbconn);
        {
            String query = "UPDATE gpsdata SET location = '";
            query << location;
            query << "' ";
            query << "WHERE gpsdataid = '";
            query << gpsdataid;
            query << "';";
            sqlite3_command cmd(*m_dbconn, std::string(query.toUTF8().getAddress()));
            cmd.executenonquery();
        }
        trans.commit();
        result = true;
    }
    CATCHDBERRORS
    return result;
}
bool Process::openDocument (const String& fileName, const String& parameters)
{
    String cmdString (fileName.replace (" ", "\\ ",false));
    cmdString << " " << parameters;

    if (URL::isProbablyAWebsiteURL (fileName)
         || cmdString.startsWithIgnoreCase ("file:")
         || URL::isProbablyAnEmailAddress (fileName)
         || File::createFileWithoutCheckingPath (fileName).isDirectory()
         || ! isFileExecutable (fileName))
    {
        // create a command that tries to launch a bunch of likely browsers
        const char* const browserNames[] = { "xdg-open", "firefox", "seamonkey",
                                             "chrome", "opera", "konqueror" };
        StringArray cmdLines;

        for (int i = 0; i < numElementsInArray (browserNames); ++i)
            cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());

        cmdString = cmdLines.joinIntoString (" || ");
    }

    const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };

    const int cpid = fork();

    if (cpid == 0)
    {
        setsid();

        // Child process
        execve (argv[0], (char**) argv, environ);
        exit (0);
    }

    return cpid >= 0;
}
 bool overwriteFileWithNewDataIfDifferent (const File& file, const String& newData)
 {
     const char* const utf8 = newData.toUTF8();
     return overwriteFileWithNewDataIfDifferent (file, utf8, strlen (utf8));
 }
//==============================================================================
WrappedJucePlugin::WrappedJucePlugin (PluginDescription* desc, bool isInternal)
:
   instance(0),
   isInternalPlugin(isInternal)
{
   if (desc)
   {
      pluginDescription = *desc;
      String errorMessage;
      
      String oldPluginFilePath = pluginDescription.fileOrIdentifier;

      // force path to be inside the app instead of wherever the plugin was in the saved session (so we don't depend on e.g. the debug version!)
      if (isInternalPlugin)
      {
         // put this somewhere shared!
         File internalPluginFolder = File::getSpecialLocation(File::currentApplicationFile).getChildFile("./Contents/PlugIns");
         
         File pluginFile = File(oldPluginFilePath);
         File localToAppPluginFile = internalPluginFolder.getChildFile(pluginFile.getFileName());

         pluginDescription.fileOrIdentifier = localToAppPluginFile.getFullPathName();

         instance = AudioPluginFormatManager::getInstance()->createPluginInstance (pluginDescription, errorMessage);
         if (!instance) // fall back to previous location!
         {
            pluginDescription.fileOrIdentifier = oldPluginFilePath;
            instance = AudioPluginFormatManager::getInstance()->createPluginInstance (pluginDescription, errorMessage);
            
            std::cerr << "Internal plugin missing - using referred file instead - " << oldPluginFilePath.toUTF8() << std::endl;
         }
      }
      else
         instance = AudioPluginFormatManager::getInstance()->createPluginInstance (pluginDescription, errorMessage);

      loadPluginStuff();
   }
}
Example #29
0
//==============================================================================
String File::parseAbsolutePath (const String& p)
{
    if (p.isEmpty())
        return String::empty;

#if JUCE_WINDOWS
    // Windows..
    String path (p.replaceCharacter ('/', '\\'));

    if (path.startsWithChar (File::separator))
    {
        if (path[1] != File::separator)
        {
            /*  When you supply a raw string to the File object constructor, it must be an absolute path.
                If you're trying to parse a string that may be either a relative path or an absolute path,
                you MUST provide a context against which the partial path can be evaluated - you can do
                this by simply using File::getChildFile() instead of the File constructor. E.g. saying
                "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
                path if that's what was supplied, or would evaluate a partial path relative to the CWD.
            */
            jassertfalse;

            path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
        }
    }
    else if (! path.containsChar (':'))
    {
        /*  When you supply a raw string to the File object constructor, it must be an absolute path.
            If you're trying to parse a string that may be either a relative path or an absolute path,
            you MUST provide a context against which the partial path can be evaluated - you can do
            this by simply using File::getChildFile() instead of the File constructor. E.g. saying
            "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
            path if that's what was supplied, or would evaluate a partial path relative to the CWD.
        */
        jassertfalse;

        return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
    }
#else
    // Mac or Linux..

    // Yes, I know it's legal for a unix pathname to contain a backslash, but this assertion is here
    // to catch anyone who's trying to run code that was written on Windows with hard-coded path names.
    // If that's why you've ended up here, use File::getChildFile() to build your paths instead.
    jassert ((! p.containsChar ('\\')) || (p.indexOfChar ('/') >= 0 && p.indexOfChar ('/') < p.indexOfChar ('\\')));

    String path (p);

    if (path.startsWithChar ('~'))
    {
        if (path[1] == File::separator || path[1] == 0)
        {
            // expand a name of the form "~/abc"
            path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
                    + path.substring (1);
        }
        else
        {
            // expand a name of type "~dave/abc"
            const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));

            struct passwd* const pw = getpwnam (userName.toUTF8());
            if (pw != nullptr)
                path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
        }
    }
    else if (! path.startsWithChar (File::separator))
    {
        /*  When you supply a raw string to the File object constructor, it must be an absolute path.
            If you're trying to parse a string that may be either a relative path or an absolute path,
            you MUST provide a context against which the partial path can be evaluated - you can do
            this by simply using File::getChildFile() instead of the File constructor. E.g. saying
            "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
            path if that's what was supplied, or would evaluate a partial path relative to the CWD.
        */
        jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)

        return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
    }
#endif

    while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
        path = path.dropLastCharacters (1);

    return path;
}
Example #30
0
    static bool connectSocket (int volatile& handle,
                               const bool isDatagram,
                               struct addrinfo** const serverAddress,
                               const String& hostName,
                               const int portNumber,
                               const int timeOutMillisecs) noexcept
    {
        struct addrinfo hints;
        zerostruct (hints);

        hints.ai_family = AF_UNSPEC;
        hints.ai_socktype = isDatagram ? SOCK_DGRAM : SOCK_STREAM;
        hints.ai_flags = AI_NUMERICSERV;

        struct addrinfo* info = nullptr;
        if (getaddrinfo (hostName.toUTF8(), String (portNumber).toUTF8(), &hints, &info) != 0
             || info == nullptr)
            return false;

        if (handle < 0)
            handle = (int) socket (info->ai_family, info->ai_socktype, 0);

        if (handle < 0)
        {
            freeaddrinfo (info);
            return false;
        }

        if (isDatagram)
        {
            if (*serverAddress != nullptr)
                freeaddrinfo (*serverAddress);

            *serverAddress = info;
            return true;
        }

        setSocketBlockingState (handle, false);
        const int result = ::connect (handle, info->ai_addr, (socklen_t) info->ai_addrlen);
        freeaddrinfo (info);

        if (result < 0)
        {
           #if JUCE_WINDOWS
            if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
           #else
            if (errno == EINPROGRESS)
           #endif
            {
                if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
                {
                    setSocketBlockingState (handle, true);
                    return false;
                }
            }
        }

        setSocketBlockingState (handle, true);
        resetSocketOptions (handle, false, false);

        return true;
    }