Write sitemap.xml to java webapp root directory permission denied

时间秒杀一切 提交于 2019-12-11 11:08:31

问题


I'm trying to use the sitemapgen4j library to build my sitemaps. I'm facing a permission problem while trying to write to my root directory

https://code.google.com/p/sitemapgen4j/

the root context folder (/src/main/webapp)

Exception

Problem writing sitemap file /sitemap.xml 
java.io.FileNotFoundException
/sitemap.xml (Permission denied)

Code

File directory = new File("/");
WebSitemapGenerator wsg = new WebSitemapGenerator("http://localhost:8080/app", directory);

Does anybody know how to go about doing this?


回答1:


I create a temp directory to store the sitemap file(s) in and then generate it on first request and serve up that same version for all subsequent requests because the data in my app doesn't change once it's started.

The benefit of using a temp directory is that you'll definitely be able to write to it (at least I think so).

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.charset.Charset;
import java.io.BufferedReader;

private Path sitemapDirectory;

@RequestMapping("/sitemap.xml")
public void sitemap(HttpServletResponse response) throws IOException {
    PrintWriter w = response.getWriter();
    boolean isSitemapAlreadyCreated = sitemapDirectory != null;
    if (isSitemapAlreadyCreated) {
        pipeSitemapToResponse(w);
        return;
    }
    sitemapDirectory = Files.createTempDirectory("mySitemap");
    WebSitemapGenerator wsg = new WebSitemapGenerator("http://localhost:8080/app", sitemapDirectory.toFile());
    wsg.addUrl("http://localhost:8080/app/home");
    wsg.write();
    pipeSitemapToResponse(w);
}

private void pipeSitemapToResponse(PrintWriter w) {
    Path sitemap = Paths.get(sitemapDir.toString(), "sitemap.xml");
    Charset charset = Charset.forName("UTF-8");
    try (BufferedReader reader = Files.newBufferedReader(sitemap, charset)) {
        String line = null;
        while ((line = reader.readLine()) != null) {
            w.write(line);
        }
    } catch (IOException e) {
        logger.error("Failed to read the sitemap file.", e);
    }
}

This solution uses Spring request mappings. It also expects the sitemap file to be written out as sitemap.xml and it will unless you have >50k entries and then you'll need to read the sitemapgen4j doco about dealing with index files and adapt this example.



来源:https://stackoverflow.com/questions/28033618/write-sitemap-xml-to-java-webapp-root-directory-permission-denied

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!