001 /*
002 * To change this template, choose Tools | Templates
003 * and open the template in the editor.
004 */
005 package net.rootdev.javardfa;
006
007 import java.io.IOException;
008 import java.io.InputStream;
009 import java.io.InputStreamReader;
010 import java.io.Reader;
011 import java.net.HttpURLConnection;
012 import java.net.MalformedURLException;
013 import java.net.URL;
014 import java.net.URLConnection;
015 import org.openrdf.model.ValueFactory;
016 import org.openrdf.repository.RepositoryConnection;
017 import org.openrdf.repository.RepositoryException;
018 import org.openrdf.repository.sail.SailRepository;
019 import org.openrdf.rio.RDFFormat;
020 import org.openrdf.rio.RDFParseException;
021 import org.openrdf.sail.SailException;
022 import org.openrdf.sail.memory.MemoryStore;
023
024 /**
025 *
026 * @author hjs
027 */
028 public class SesameUtils {
029
030 public static String getContentAsString(URL url) throws IOException {
031 URLConnection conn = url.openConnection();
032 conn.connect();
033 InputStream in = conn.getInputStream();
034 Reader r = new InputStreamReader(in, "UTF-8");
035 int c;
036 StringBuffer buf = new StringBuffer();
037 while ((c = r.read()) != -1) {
038 buf.append((char) c);
039 }
040 return buf.toString();
041 }
042
043 public static RepositoryConnection fetchResource(URL actualUrl, RDFFormat rdfFormat) throws SailException, RepositoryException, RDFParseException, IOException, MalformedURLException {
044 URL base = new URL(actualUrl.getProtocol(), actualUrl.getHost(), actualUrl.getPort(), actualUrl.getFile()); // all of this needs
045 MemoryStore mem = new MemoryStore();
046 mem.initialize();
047 SailRepository sail = new SailRepository(mem);
048 RepositoryConnection rep = sail.getConnection();
049 ValueFactory vf = sail.getValueFactory();
050 // to be better
051 org.openrdf.model.URI foafdocUri = vf.createURI(base.toString());
052 HttpURLConnection conn = (HttpURLConnection) base.openConnection();
053 conn.addRequestProperty("Accept:", rdfFormat.getDefaultMIMEType());
054 conn.connect();
055 InputStream foafin = conn.getInputStream();
056 rep.add(foafin, actualUrl.toString(), rdfFormat, foafdocUri);
057 return rep;
058 }
059 }