Внедрение зависимостей Play and Guice с интерфейсом

Первое, что вам нужно сделать, это убедиться, что файл существует. Для этого вам просто нужно попытаться открыть поток файлов на пути. После того, как вы открыли поток файлов, используйте stream.fail (), чтобы узнать, работает ли он, как ожидалось, или нет.

bool fileExists(string fileName)
{

ifstream test;

test.open(fileName.c_str());

if (test.fail())
{
    test.close();
    return false;
}
else
{
    test.close();
    return true;
}
}

Вы также должны убедиться, что указанный файл является правильным типом файла. Для этого вам нужно просмотреть путь к файлу, пока не найдете расширение файла. После того, как у вас есть расширение файла, убедитесь, что оно является CSV-файлом.

bool verifyExtension(string filename)
{
int period = 0;

for (unsigned int i = 0; i < filename.length(); i++)
{
    if (filename[i] == '.')
        period = i;
}

string extension;

for (unsigned int i = period; i < filename.length(); i++)
    extension += filename[i];

if (extension == ".csv")
    return true;
else
    return false;
}

Эта функция вернет расширение файла, которое будет использоваться позже в сообщении об ошибке.

string getExtension(string filename)
{
int period = 0;

for (unsigned int i = 0; i < filename.length(); i++)
{
    if (filename[i] == '.')
        period = i;
}

string extension;

if (period != 0)
{
    for (unsigned int i = period; i < filename.length(); i++)
        extension += filename[i];
}
else
    extension = "NO FILE";

return extension;
}

Эта функция фактически вызовет созданные выше проверки ошибок, а затем проанализирует файл.

void parseFile(string fileName)
{
    if (fileExists(fileName) && verifyExtension(fileName))
    {
        ifstream fs;
        fs.open(fileName.c_str());
        string fileCommand;

        while (fs.good())
        {
            string temp;

            getline(fs, fileCommand, '\n');

            for (unsigned int i = 0; i < fileCommand.length(); i++)
            {
                if (fileCommand[i] != ',')
                    temp += fileCommand[i];
                else
                    temp += " ";
            }

            if (temp != "\0")
            {
                // Place your code here to run the file.
            }
        }
        fs.close();
    }
    else if (!fileExists(fileName))
    {
        cout << "Error: The provided file does not exist: " << fileName << endl;

        if (!verifyExtension(fileName))
        {
            if (getExtension(fileName) != "NO FILE")
                cout << "\tCheck the file extension." << endl;
            else
                cout << "\tThere is no file in the provided path." << endl;
        }
    }
    else if (!verifyExtension(fileName)) 
    {
        if (getExtension(fileName) != "NO FILE")
            cout << "Incorrect file extension provided: " << getExtension(fileName) << endl;
        else
            cout << "There is no file in the following path: " << fileName << endl;
    }
}
0
задан user3564870 19 February 2019 в 21:44
поделиться

1 ответ

Вы можете использовать аннотацию guice @ImplementedBy следующим образом:

import com.google.inject.ImplementedBy;

@ImplementedBy(Service.class)
public interface IService {
    Result handleRequest();
}

Или вы можете использовать такие модули:

import com.google.inject.AbstractModule;

public class ServiceModule extends AbstractModule {

    protected void configure() {
        bind(IService.class).to(Service.class);
    }
}

И затем зарегистрировать их в application.conf [113 ]

0
ответ дан Tijkijiki 19 February 2019 в 21:44
поделиться
Другие вопросы по тегам:

Похожие вопросы: