Newer
Older
IrisServerWebSocket / src / main / java / com / ntlab / irisserver / models / KeywordManager.java
Kota on 8 Dec 2022 1 KB first commit
package com.ntlab.irisserver.models;

import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;


@Component
public class KeywordManager {

    private static KeywordManager theInstance = null;
    String[] keywords = {"0"};

    //シングルトンパターンでインスタンス作成
    public static KeywordManager getInstance() {
        if(theInstance == null) {
            theInstance = new KeywordManager();
        }
        return theInstance;
    }

    //------------------------------------------------------------------------------
    //読み込んだファイルのキーワードをStringの配列で返す
    public String[] getKeywords(String path){
        var response = Response.status(Response.Status.NO_CONTENT);

        if(path == null){
            response.status(400).entity("パスがありません");
            throw new WebApplicationException(response.build());
        } else if(FileRead(path).size() == 0){
            response.status(404).entity(path+"に対応したファイルがありません");
            throw new WebApplicationException(response.build());
        } else {
            keywords = FileRead(path).toArray(new String[FileRead(path).size()]);
        }

        return keywords;
    }

    //-----------------------------------------------------------------------------
    //pathのファイルを読み込み
    private List<String> FileRead(String path) {
        List<String> ss = new ArrayList<String>();

        try {
            BufferedReader buffReader = new BufferedReader(new FileReader(path));
            String s;
            while ((s = buffReader.readLine()) != null) {
                ss.add(s);
            }

            buffReader.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return ss;
    }

}