import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
@Component
public class FileDownLoader {
public void donwLoadFile(String fileName) throws IOException, ParseException{
FileTime beforeT = null;
Path path = Paths.get("/localpath/" + fileName);
try{
//更新前ファイルのタイムスタンプ取得
beforeT = Files.getLastModifiedTime(path);
} catch (Exception ex) {
//新規ファイル
}
String url = "http://filestore.bbb.co.jp/web/download/" +fileName;
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new NTCredentials("username", "password", null, null));
HttpGet httpGet = new HttpGet(url);
CloseableHttpClient httpclient = HttpClientBuilder
.create()
.setDefaultCredentialsProvider(credentialsProvider)
.build();
CloseableHttpResponse closeableHttpResponse = httpclient.execute(httpGet);
FileTime modTime = beforeT;
if( closeableHttpResponse.getAllHeaders() != null){
DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
modTime = FileTime.from(df.parse(closeableHttpResponse.getFirstHeader("Last-Modified").getValue()).toInstant());
}
//更新無し
if(beforeT != null && beforeT.compareTo(modTime) == 0){
closeableHttpResponse.close();
return;
}
Files.write(path, EntityUtils.toByteArray(closeableHttpResponse.getEntity()));
//更新日時タイムスタンプ書き換え
Files.setLastModifiedTime(path, modTime);
closeableHttpResponse.close();
}
}