Spring Boot WebDav内のファイルリストを取得

Spring Boot

この記事では、JavaのSpring Bootを利用してWebDav内に保存されているファイルのリストを取得する方法を解説します。

JavaLearning

よく利用する処理を書き出す

WebDavサーバの情報を保持するオブジェクトクラスを作成する

オブジェクトクラスにWebDavのURLや、認証のためのユーザーやパスワードを持たせておきます。

package com.example;

public class WebDavServerObject {
    
    private Integer davId;
    private String davName;
    private String davUrl;
    private String davUserId;
    private String davUserPass;



    public Integer getDavId() {
        return this.davId;
    }

    public void setDavId(Integer davId) {
        this.davId = davId;
    }

    public String getDavName() {
        return this.davName;
    }

    public void setDavName(String davName) {
        this.davName = davName;
    }

    public String getDavUrl() {
        return this.davUrl;
    }

    public void setDavUrl(String davUrl) {
        this.davUrl = davUrl;
    }

    public String getDavUserId() {
        return this.davUserId;
    }

    public void setDavUserId(String davUserId) {
        this.davUserId = davUserId;
    }

    public String getDavUserPass() {
        return this.davUserPass;
    }

    public void setDavUserPass(String davUserPass) {
        this.davUserPass = davUserPass;
    }
}

認証情報を作成する

WebDavを利用する際には、Basic認証が必要になることがよくあります。
その場合認証情報を作成するメソッドは、よく利用するのであらかじめ書き出しておきます。

// 認証情報作成
private static String getAuthorizationString(String username, String password) {
    String userpass = username + ":" + password;
    return Base64.getEncoder().encodeToString(userpass.getBytes());
}

ファイルやフォルダが存在するかを確認する

WebDav内のファイルやフォルダの存在を確認するメソッドもよく利用するのであらかじめ書き出しておきます。

// WebDavフォルダの存在確認
private static boolean checkWebDavFolderExistence(String webdavUrl, String username, String password) {
    try {
        URL url = new URL(webdavUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("HEAD");
        connection.setRequestProperty("Authorization", "Basic "
            + getAuthorizationString(username, password));
        int responseCode = connection.getResponseCode();
        connection.disconnect();
        return responseCode == HttpURLConnection.HTTP_OK;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

ファイルリストを取得する

あらかじめ作っておいたメソッドを利用しながら、WebDavに保存されているファイルのリストを取得します。
戻り値はファイル名のリストとして作成します。

public List<String> getFileList(WebDavServerObject davServer) throws IOException {
    
    String webdavServerUrl = davServer.getDavUrl() + "/folderPath/";
    List<String> strList = new ArrayList<String>();
    try {
        // WebDavフォルダの存在確認
        if (!checkWebDavFolderExistence(webdavServerUrl, davServer.getDavUserId(), davServer.getDavUserPass())) {
            System.out.println("WebDavフォルダが存在しません。");
            return strList;
        }

        // ファイル一覧の取得
        URL url = new URL(webdavServerUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("GET");  // GET メソッドに変更
        connection.setRequestProperty("Content-Type", "text/xml");
        connection.setRequestProperty("Depth", "1");
        connection.setRequestProperty("Authorization", "Basic "
            + getAuthorizationString(davServer.getDavUserId(), davServer.getDavUserPass()));

        InputStream is = connection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String html;
        while ((html = br.readLine()) != null) {
            Document doc = Jsoup.parse(html);
            Elements links = doc.select("a");
            for (Element link : links) {
                if (!"../".equals(link.attr("href"))) {
                    strList.add(URLDecoder.decode(link.attr("href"), "UTF-8"));
                }
            }
        }
        br.close();

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

    return strList;
}

今まで紹介したメソッドは、WebDavサーバの情報を保持するオブジェクトクラス意外全てをサービスクラスに記載します。
全てをまとめると、サービスクラスは以下のようになります。

package com.example

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import com.example.WebDavServerObject;


@Service
public class WebdavFileManagementService {

public List<String> getFileList(WebDavServerObject davServer) throws IOException {
    
    String webdavServerUrl = davServer.getDavUrl() + "/folderPath/";
    List<String> strList = new ArrayList<String>();
    try {
        // WebDavフォルダの存在確認
        if (!checkWebDavFolderExistence(webdavServerUrl, davServer.getDavUserId(), davServer.getDavUserPass())) {
            System.out.println("WebDavフォルダが存在しません。");
            return strList;
        }

        // ファイル一覧の取得
        URL url = new URL(webdavServerUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("GET");  // GET メソッドに変更
        connection.setRequestProperty("Content-Type", "text/xml");
        connection.setRequestProperty("Depth", "1");
        connection.setRequestProperty("Authorization", "Basic "
            + getAuthorizationString(davServer.getDavUserId(), davServer.getDavUserPass()));

        InputStream is = connection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String html;
        while ((html = br.readLine()) != null) {
            Document doc = Jsoup.parse(html);
            Elements links = doc.select("a");
            for (Element link : links) {
                if (!"../".equals(link.attr("href"))) {
                    strList.add(URLDecoder.decode(link.attr("href"), "UTF-8"));
                }
            }
        }
        br.close();

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

    return strList;
}


// 認証情報作成
private static String getAuthorizationString(String username, String password) {
    String userpass = username + ":" + password;
    return Base64.getEncoder().encodeToString(userpass.getBytes());
}


// WebDavフォルダの存在確認
private static boolean checkWebDavFolderExistence(String webdavUrl, String username, String password) {
    try {
        URL url = new URL(webdavUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("HEAD");
        connection.setRequestProperty("Authorization", "Basic "
            + getAuthorizationString(username, password));
        int responseCode = connection.getResponseCode();
        connection.disconnect();
        return responseCode == HttpURLConnection.HTTP_OK;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

}

コントローラークラスから呼び出す

WebDavに書き込むメソッドを呼び出すコントローラークラスを作成します。
ブラウザなどからファイルリスト取得の命令を受け取るのは、このコントローラークラスになります。

package com.example;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.example.WebDavServerObject;

@RestController
public class WebdavApiManagementController {

    @Autowired
    private WebdavFileManagementService webdavFileManagementService;


    @PostMapping(value="/filelist")
    public String getFileList() {

        // 適切にWebDavServer情報を取得するよう書き換えてください
        WebDavServerObject davServer = new WebDavServerObject();
        ObjectMapper objectMapper = new ObjectMapper();
        String json = "";

        try {
            json = objectMapper.writeValueAsString(webdavFileManagementService.getFileList(davServer));
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        return json;
    }
}

まとめ

今回は、WebDavに保存されているファイルのリストを取得する方法を解説しました。
他にもWebDavに関する以下の記事を公開していますので、よろしければそちらもご覧ください。

それでは〜。

コメント

タイトルとURLをコピーしました