You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@marmotta.apache.org by wi...@apache.org on 2013/02/19 13:52:00 UTC
[21/52] [partial] code contribution,
initial import of relevant modules of LMF-3.0.0-SNAPSHOT based on
revision 4bf944319368 of the default branch at https://code.google.com/p/lmf/
http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/c32963d5/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/ClassificationClient.java
----------------------------------------------------------------------
diff --git a/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/ClassificationClient.java b/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/ClassificationClient.java
new file mode 100644
index 0000000..9e6aee6
--- /dev/null
+++ b/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/ClassificationClient.java
@@ -0,0 +1,362 @@
+/**
+ * Copyright (C) 2013 Salzburg Research.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package at.newmedialab.lmf.client.clients;
+
+import at.newmedialab.lmf.client.ClientConfiguration;
+import at.newmedialab.lmf.client.exception.LMFClientException;
+import at.newmedialab.lmf.client.model.classification.Classification;
+import at.newmedialab.lmf.client.model.rdf.URI;
+import at.newmedialab.lmf.client.util.HTTPUtil;
+import com.google.common.base.Preconditions;
+import com.google.common.io.ByteStreams;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpDelete;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.ContentProducer;
+import org.apache.http.entity.EntityTemplate;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.codehaus.jackson.type.TypeReference;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * A client supporting access to the LMF Classification Services. Allows creating and removing classifiers as
+ * well as training classifiers with sample data and the classification of textual documents.
+ * <p/>
+ * Author: Sebastian Schaffert
+ */
+public class ClassificationClient {
+
+ private static Logger log = LoggerFactory.getLogger(ClassificationClient.class);
+
+ private static final String URL_CLASSIFICATION_SERVICE = "/classifier";
+
+
+ private ClientConfiguration config;
+
+ public ClassificationClient(ClientConfiguration config) {
+ this.config = config;
+ }
+
+
+ /**
+ * Create a new classifier with the given name. The service will take care of creating the appropriate
+ * configuration entries and work files in the LMF work directory.
+ *
+ * @param name a string identifying the classifier; should only consist of alphanumeric characters (no white spaces)
+ */
+ public boolean createClassifier(String name) throws LMFClientException, IOException {
+ Preconditions.checkArgument(name.matches("^\\p{Alnum}+$"));
+
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ HttpPost post = new HttpPost(config.getLmfUri() + URL_CLASSIFICATION_SERVICE + "/" + name);
+
+ try {
+
+ HttpResponse response = httpClient.execute(post);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 403:
+ log.debug("classifier {} already existed, not creating new",name);
+ return true;
+ case 200:
+ log.debug("classifier {} created",name);
+ return true;
+ default:
+ log.error("error creating classifier {}: {} {}",new Object[] {name,response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ return true;
+ }
+
+ } catch (UnsupportedEncodingException e) {
+ log.error("could not encode URI parameter",e);
+ return false;
+ } finally {
+ post.releaseConnection();
+ }
+ }
+
+
+ /**
+ * Remove the classifier with the given name from the system configuration.
+ *
+ * @param name a string identifying the classifier; should only consist of alphanumeric characters (no white spaces)
+ * @param removeData also remove all training and model data of this classifier from the file system
+ */
+ public void removeClassifier(String name, boolean removeData) throws LMFClientException, IOException {
+ Preconditions.checkArgument(name.matches("^\\p{Alnum}+$"));
+
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ HttpDelete delete = new HttpDelete(config.getLmfUri() + URL_CLASSIFICATION_SERVICE + "/" + name + (removeData?"?removeData=true":""));
+
+ try {
+
+ HttpResponse response = httpClient.execute(delete);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("classifier {} deleted", name);
+ break;
+ case 404:
+ log.error("classifier {} does not exist, cannot delete", name);
+ break;
+ default:
+ log.error("error deleting classifier {}: {} {}",new Object[] {name,response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ }
+
+ } catch (UnsupportedEncodingException e) {
+ delete.abort();
+ log.error("could not encode URI parameter",e);
+ } finally {
+ delete.releaseConnection();
+ }
+ }
+
+
+ /**
+ * List all classifiers registered in the classification service.
+ *
+ * @return a collection of Classifier instances representing all registered classifiers
+ */
+ public Collection<String> listClassifiers() throws IOException, LMFClientException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ String serviceUrl = config.getLmfUri() + URL_CLASSIFICATION_SERVICE + "/list";
+
+ HttpGet get = new HttpGet(serviceUrl);
+ get.setHeader("Accept", "application/json");
+
+ try {
+
+ HttpResponse response = httpClient.execute(get);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("classifiers listed successfully");
+ ObjectMapper mapper = new ObjectMapper();
+ List<String> result = mapper.readValue(response.getEntity().getContent(),new TypeReference<List<String>>(){});
+
+ return result;
+ default:
+ log.error("error retrieving list of classifiers: {} {}",new Object[] {response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ throw new LMFClientException("error retrieving list of classifiers: "+response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
+ }
+
+ } finally {
+ get.releaseConnection();
+ }
+ }
+
+
+ /**
+ * Add training data to the classifier identified by the given name and for the concept passed as argument. Note
+ * that training data is not immediately taken into account by the classifier. Retraining of the classifier will
+ * take place when a certain threshold of training datasets has been added or when a certain (configurable) time has
+ * passed.
+ *
+ * @param name a string identifying the classifier; should only consist of alphanumeric characters (no white spaces)
+ * @param concept_uri the URI of the concept which to train with the sample text
+ * @param sampleText the sample text for the concept
+ */
+ public void trainClassifier(String name, String concept_uri, final String sampleText) throws LMFClientException, IOException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ String serviceUrl = config.getLmfUri() + URL_CLASSIFICATION_SERVICE + "/" + URLEncoder.encode(name,"utf-8") + "/train?concept=" + URLEncoder.encode(concept_uri,"utf-8");
+
+ HttpPost post = new HttpPost(serviceUrl);
+ post.setHeader("Content-Type", "text/plain");
+
+ ContentProducer cp = new ContentProducer() {
+ @Override
+ public void writeTo(OutputStream outstream) throws IOException {
+ ByteStreams.copy(new ByteArrayInputStream(sampleText.getBytes("utf-8")), outstream);
+ }
+ };
+
+ post.setEntity(new EntityTemplate(cp));
+
+ try {
+
+ HttpResponse response = httpClient.execute(post);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("classifier {} updated successfully",name);
+ break;
+ default:
+ log.error("error updating classifier {}: {} {}",new Object[] {name,response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ throw new LMFClientException("error updating classifier "+name+": "+response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
+ }
+
+ } finally {
+ post.releaseConnection();
+ }
+ }
+
+
+ /**
+ * Retrain the classifier with the given name immediately. Will read in the training data and create a new
+ * classification model.
+ *
+ * @param name
+ * @throws LMFClientException
+ */
+ public void retrainClassifier(String name) throws LMFClientException, IOException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ String serviceUrl = config.getLmfUri() + URL_CLASSIFICATION_SERVICE + "/" + URLEncoder.encode(name,"utf-8") + "/retrain";
+
+ HttpPost post = new HttpPost(serviceUrl);
+
+ try {
+
+ HttpResponse response = httpClient.execute(post);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("classifier {} retrained successfully",name);
+ break;
+ default:
+ log.error("error retraining classifier {}: {} {}",new Object[] {name,response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ throw new LMFClientException("error updating classifier "+name+": "+response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
+ }
+
+ } finally {
+ post.releaseConnection();
+ }
+ }
+
+
+ /**
+ * Get classifications from the given classifier for the given text. The classifications will be ordered by
+ * descending probability, so that classifications with higher probability will be first. A classification object
+ * consists of a KiWiUriResource identifying the classified concept and a probability indicating how likely it is
+ * that the text matches the given concept.
+ *
+ * @param classifier a string identifying the classifier; should only consist of alphanumeric characters (no white spaces)
+ * @param text the text to classify
+ * @return a list of classifications ordered by descending probability
+ */
+ public List<Classification> getAllClassifications(String classifier, final String text) throws LMFClientException, IOException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ String serviceUrl = config.getLmfUri() + URL_CLASSIFICATION_SERVICE + "/" + classifier+"/classify";
+
+ HttpPost post = new HttpPost(serviceUrl);
+ post.setHeader("Content-Type", "text/plain");
+
+ ContentProducer cp = new ContentProducer() {
+ @Override
+ public void writeTo(OutputStream outstream) throws IOException {
+ ByteStreams.copy(new ByteArrayInputStream(text.getBytes("utf-8")), outstream);
+ }
+ };
+
+ post.setEntity(new EntityTemplate(cp));
+
+ try {
+
+ HttpResponse response = httpClient.execute(post);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("classification {} executed successfully",classifier);
+ ObjectMapper mapper = new ObjectMapper();
+ List<Map<String,String>> jsonResult =
+ mapper.readValue(response.getEntity().getContent(),new TypeReference<List<Map<String,String>>>(){});
+
+ List<Classification> result = new LinkedList<Classification>();
+ for(Map<String,String> entry : jsonResult) {
+ result.add(new Classification(new URI(entry.get("concept")), Double.parseDouble(entry.get("probability"))));
+ }
+ return result;
+ default:
+ log.error("error executing classifier {}: {} {}",new Object[] {classifier,response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ throw new LMFClientException("error executing classifier "+classifier+": "+response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
+ }
+
+ } finally {
+ post.releaseConnection();
+ }
+ }
+
+
+ /**
+ * Get classifications from the given classifier for the given text. The classifications will be ordered by
+ * descending probability, so that classifications with higher probability will be first. Only classifications with
+ * a probability higher than the threshold will be considered. A classification object
+ * consists of a KiWiUriResource identifying the classified concept and a probability indicating how likely it is
+ * that the text matches the given concept.
+ *
+ * @param classifier a string identifying the classifier; should only consist of alphanumeric characters (no white spaces)
+ * @param text the text to classify
+ * @param threshold the minimum probability of a classification to be considered in the result
+ * @return a list of classifications ordered by descending probability, all having higher probability than threshold
+ */
+ public List<Classification> getAllClassifications(String classifier, final String text, double threshold) throws LMFClientException, IOException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ String serviceUrl = config.getLmfUri() + URL_CLASSIFICATION_SERVICE + "/" + classifier+"/classify?threshold="+threshold;
+
+ HttpPost post = new HttpPost(serviceUrl);
+ post.setHeader("Content-Type", "text/plain");
+ ContentProducer cp = new ContentProducer() {
+ @Override
+ public void writeTo(OutputStream outstream) throws IOException {
+ ByteStreams.copy(new ByteArrayInputStream(text.getBytes("utf-8")), outstream);
+ }
+ };
+ post.setEntity(new EntityTemplate(cp));
+
+ try {
+ HttpResponse response = httpClient.execute(post);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("classification {} executed successfully",classifier);
+ ObjectMapper mapper = new ObjectMapper();
+ List<Map<String,String>> jsonResult =
+ mapper.readValue(response.getEntity().getContent(),new TypeReference<List<Map<String,String>>>(){});
+
+ List<Classification> result = new LinkedList<Classification>();
+ for(Map<String,String> entry : jsonResult) {
+ result.add(new Classification(new URI(entry.get("concept")), Double.parseDouble(entry.get("probability"))));
+ }
+ return result;
+ default:
+ log.error("error executing classifier {}: {} {}",new Object[] {classifier,response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ throw new LMFClientException("error executing classifier "+classifier+": "+response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
+ }
+
+ } finally {
+ post.releaseConnection();
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/c32963d5/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/ConfigurationClient.java
----------------------------------------------------------------------
diff --git a/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/ConfigurationClient.java b/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/ConfigurationClient.java
new file mode 100644
index 0000000..1d5dd5a
--- /dev/null
+++ b/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/ConfigurationClient.java
@@ -0,0 +1,264 @@
+/**
+ * Copyright (C) 2013 Salzburg Research.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package at.newmedialab.lmf.client.clients;
+
+import at.newmedialab.lmf.client.ClientConfiguration;
+import at.newmedialab.lmf.client.exception.LMFClientException;
+import at.newmedialab.lmf.client.exception.NotFoundException;
+import at.newmedialab.lmf.client.model.config.Configuration;
+import at.newmedialab.lmf.client.util.HTTPUtil;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpDelete;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.ContentProducer;
+import org.apache.http.entity.EntityTemplate;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.codehaus.jackson.type.TypeReference;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.URLEncoder;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A client that supports accessing the configuration webservice of the Linked Media Framework. May be used for
+ * retrieving as well as changing properties.
+ *
+ * <p/>
+ * Author: Sebastian Schaffert
+ */
+public class ConfigurationClient {
+ private static Logger log = LoggerFactory.getLogger(ConfigurationClient.class);
+
+ private static final String URL_CONFIG_SERVICE = "/config";
+
+
+ private ClientConfiguration config;
+
+ public ConfigurationClient(ClientConfiguration config) {
+ this.config = config;
+ }
+
+ /**
+ * Return a list of all configuration keys that are currently set in the LMF configuration.
+ * @return
+ * @throws IOException
+ * @throws LMFClientException
+ */
+ public Set<String> listConfigurationKeys() throws IOException, LMFClientException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ HttpGet get = new HttpGet(config.getLmfUri() + URL_CONFIG_SERVICE + "/list");
+ get.setHeader("Accept", "application/json");
+
+ try {
+
+ HttpResponse response = httpClient.execute(get);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("configurations listed successfully");
+ ObjectMapper mapper = new ObjectMapper();
+ Map<String,Map<String,Object>> result =
+ mapper.readValue(response.getEntity().getContent(),new TypeReference<Map<String,Map<String,Object>>>(){});
+ return result.keySet();
+ default:
+ log.error("error retrieving list of configuration keys: {} {}",new Object[] {response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ throw new LMFClientException("error retrieving list of configuration keys: "+response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
+ }
+
+ } finally {
+ get.releaseConnection();
+ }
+ }
+
+ /**
+ * Return a list of all configurations (keys and values) that are currently set in the LMF configuration.
+ * @return
+ * @throws IOException
+ * @throws LMFClientException
+ */
+ public Set<Configuration> listConfigurations(String prefix) throws IOException, LMFClientException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ String serviceUrl = config.getLmfUri() + URL_CONFIG_SERVICE + "/list" + (prefix != null? "?prefix="+ URLEncoder.encode(prefix,"utf-8") : "");
+
+ HttpGet get = new HttpGet(serviceUrl);
+ get.setHeader("Accept", "application/json");
+
+ try {
+
+ HttpResponse response = httpClient.execute(get);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("configurations listed successfully");
+ ObjectMapper mapper = new ObjectMapper();
+ Map<String,Map<String,Object>> resultMap =
+ mapper.readValue(response.getEntity().getContent(),new TypeReference<Map<String,Map<String,Object>>>(){});
+
+ Set<Configuration> result = new HashSet<Configuration>();
+ for(Map.Entry<String,Map<String,Object>> entry : resultMap.entrySet()) {
+ result.add(new Configuration(entry.getKey(),entry.getValue().get("value")));
+ }
+ return result;
+ default:
+ log.error("error retrieving list of configuration keys: {} {}",new Object[] {response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ throw new LMFClientException("error retrieving list of configuration keys: "+response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
+ }
+
+ } finally {
+ get.releaseConnection();
+ }
+ }
+
+
+ /**
+ * Return the configuration with the given key, or null if it does not exist
+ * @param key
+ * @return
+ * @throws IOException
+ * @throws LMFClientException
+ */
+ public Configuration getConfiguration(String key) throws IOException, LMFClientException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ String serviceUrl = config.getLmfUri() + URL_CONFIG_SERVICE + "/data/" + URLEncoder.encode(key,"utf-8");
+
+ HttpGet get = new HttpGet(serviceUrl);
+ get.setHeader("Accept", "application/json");
+
+ try {
+
+ HttpResponse response = httpClient.execute(get);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("configuration {} retrieved successfully",key);
+ ObjectMapper mapper = new ObjectMapper();
+ Map<String,Object> resultMap =
+ mapper.readValue(response.getEntity().getContent(),new TypeReference<Map<String,Object>>(){});
+
+ if(resultMap.isEmpty()) {
+ return null;
+ } else {
+ return new Configuration(key,resultMap.get(key));
+ }
+ case 404:
+ log.info("configuration with key {} does not exist", key);
+ return null;
+ default:
+ log.error("error retrieving configuration {}: {} {}",new Object[] {key,response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ throw new LMFClientException("error retrieving configuration "+key+": "+response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
+ }
+
+ } finally {
+ get.releaseConnection();
+ }
+ }
+
+ /**
+ * Update the configuration "key" with the given value. Value can be either a list of values or one of the
+ * primitive types String, Boolean, Integer, Double
+ * @param key
+ * @param value
+ * @throws IOException
+ * @throws LMFClientException
+ */
+ public void setConfiguration(String key, final Object value) throws IOException, LMFClientException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ String serviceUrl = config.getLmfUri() + URL_CONFIG_SERVICE + "/data/" + URLEncoder.encode(key,"utf-8");
+
+ HttpPost post = new HttpPost(serviceUrl);
+ post.setHeader("Content-Type", "application/json");
+ ContentProducer cp = new ContentProducer() {
+ @Override
+ public void writeTo(OutputStream outstream) throws IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ if(value instanceof Collection) {
+ mapper.writeValue(outstream,value);
+ } else {
+ mapper.writeValue(outstream, Collections.singletonList(value.toString()));
+ }
+ }
+ };
+ post.setEntity(new EntityTemplate(cp));
+
+ try {
+
+ HttpResponse response = httpClient.execute(post);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("configuration {} updated successfully",key);
+ break;
+ case 404:
+ log.error("configuration with key {} does not exist",key);
+ throw new NotFoundException("configuration with key "+key+" does not exist");
+ default:
+ log.error("error updating configuration {}: {} {}",new Object[] {key,response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ throw new LMFClientException("error updating configuration "+key+": "+response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
+ }
+
+ } finally {
+ post.releaseConnection();
+ }
+ }
+
+ /**
+ * Remove the configuration with the given key.
+ *
+ * @param key
+ * @throws IOException
+ * @throws LMFClientException
+ */
+ public void deleteConfiguration(String key) throws IOException, LMFClientException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ String serviceUrl = config.getLmfUri() + URL_CONFIG_SERVICE + "/data/" + URLEncoder.encode(key,"utf-8");
+
+ HttpDelete delete = new HttpDelete(serviceUrl);
+
+ try {
+ HttpResponse response = httpClient.execute(delete);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("configuration {} deleted successfully",key);
+ break;
+ case 404:
+ log.error("configuration with key {} does not exist",key);
+ throw new NotFoundException("configuration with key "+key+" does not exist");
+ default:
+ log.error("error deleting configuration {}: {} {}",new Object[] {key,response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ throw new LMFClientException("error deleting configuration "+key+": "+response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
+ }
+
+ } finally {
+ delete.releaseConnection();
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/c32963d5/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/ContextClient.java
----------------------------------------------------------------------
diff --git a/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/ContextClient.java b/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/ContextClient.java
new file mode 100644
index 0000000..a066e47
--- /dev/null
+++ b/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/ContextClient.java
@@ -0,0 +1,80 @@
+/**
+ * Copyright (C) 2013 Salzburg Research.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package at.newmedialab.lmf.client.clients;
+
+import at.newmedialab.lmf.client.ClientConfiguration;
+import at.newmedialab.lmf.client.util.HTTPUtil;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpDelete;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+
+/**
+ * Context Client
+ *
+ * @author Sergio Fernández
+ *
+ */
+public class ContextClient {
+
+ private static Logger log = LoggerFactory.getLogger(ContextClient.class);
+
+ private ClientConfiguration config;
+
+ public ContextClient(ClientConfiguration config) {
+ this.config = config;
+ }
+
+ public boolean delete(String uri) {
+ boolean result = false;
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ HttpDelete delete = new HttpDelete(uri);
+
+ try {
+
+ HttpResponse response = httpClient.execute(delete);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug(uri + "cleanned");
+ result = true;
+ break;
+ case 404:
+ log.error(uri + " is not a suitable context");
+ result = false;
+ default:
+ log.error("error cleanning context: {} {}",new Object[] {response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ }
+
+ } catch (ClientProtocolException e) {
+ log.error(e.getMessage(), e);
+ result = false;
+ } catch (IOException e) {
+ log.error(e.getMessage(), e);
+ result = false;
+ } finally {
+ delete.releaseConnection();
+ }
+ return result;
+
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/c32963d5/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/CoresClient.java
----------------------------------------------------------------------
diff --git a/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/CoresClient.java b/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/CoresClient.java
new file mode 100644
index 0000000..4092a55
--- /dev/null
+++ b/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/CoresClient.java
@@ -0,0 +1,297 @@
+/**
+ * Copyright (C) 2013 Salzburg Research.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package at.newmedialab.lmf.client.clients;
+
+import at.newmedialab.lmf.client.ClientConfiguration;
+import at.newmedialab.lmf.client.exception.LMFClientException;
+import at.newmedialab.lmf.client.exception.NotFoundException;
+import at.newmedialab.lmf.client.util.HTTPUtil;
+import com.google.common.io.ByteStreams;
+import com.google.common.io.CharStreams;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpDelete;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpPut;
+import org.apache.http.entity.ContentProducer;
+import org.apache.http.entity.EntityTemplate;
+import org.codehaus.jackson.JsonParser;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.codehaus.jackson.type.TypeReference;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.net.URLEncoder;
+import java.util.List;
+
+/**
+ * A client allowing to retrieve and configure the SOLR cores that are registered in the LMF server.
+ * <p/>
+ * Author: Sebastian Schaffert
+ */
+public class CoresClient {
+
+ private static Logger log = LoggerFactory.getLogger(CoresClient.class);
+
+ private static final String URL_CORES_SERVICE = "/solr/cores";
+
+ private ClientConfiguration config;
+
+ public CoresClient(ClientConfiguration config) {
+ this.config = config;
+ }
+
+
+ /**
+ * Retrieve a list of all core names registered and activated in the LMF server.
+ *
+ * @return
+ * @throws IOException
+ * @throws LMFClientException
+ */
+ public List<String> listCores() throws IOException, LMFClientException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ String serviceUrl = config.getLmfUri() + URL_CORES_SERVICE;
+
+ HttpGet get = new HttpGet(serviceUrl);
+ get.setHeader("Accept", "application/json");
+
+ try {
+
+ HttpResponse response = httpClient.execute(get);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("active cores retrieved successfully");
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
+ List<String> result =
+ mapper.readValue(response.getEntity().getContent(),new TypeReference<List<String>>(){});
+
+ return result;
+
+ default:
+ log.error("error retrieving active cores: {} {}",new Object[] {response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ throw new LMFClientException("error retrieving active cores: "+response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
+ }
+
+ } finally {
+ get.releaseConnection();
+ }
+ }
+
+ /**
+ * Return the LDPath program configured for the core with the name passed as argument.
+ *
+ * Note that this library provides no further functionality for evaluating LDPath programs. You may use the
+ * separate LDPath libraries at http://code.google.com/p/ldpath/.
+ *
+ * @param coreName name of the core for which to retrieve the LDPath program
+ * @return
+ * @throws IOException
+ * @throws LMFClientException
+ */
+ public String getCoreConfiguration(String coreName) throws IOException, LMFClientException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ String serviceUrl = config.getLmfUri() + URL_CORES_SERVICE + "/" + URLEncoder.encode(coreName,"utf-8");
+
+ HttpGet get = new HttpGet(serviceUrl);
+ get.setHeader("Accept", "text/plain");
+
+ try {
+
+ HttpResponse response = httpClient.execute(get);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("core {} retrieved successfully",coreName);
+ return CharStreams.toString(new InputStreamReader(response.getEntity().getContent(),"utf-8"));
+ default:
+ log.error("error retrieving core {}: {} {}",new Object[] {coreName,response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ throw new LMFClientException("error retrieving core "+coreName+": "+response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
+ }
+
+ } finally {
+ get.releaseConnection();
+ }
+ }
+
+ /**
+ * Create the core configuration for the given core using the LDPath program passed as argument.
+ *
+ * Note that this library provides no further functionality for evaluating LDPath programs. You may use the
+ * separate LDPath libraries at http://code.google.com/p/ldpath/.
+ *
+ * @param coreName the name of the core to update
+ * @param coreProgram the LDPath program to use as core configuration
+ * @throws IOException
+ * @throws LMFClientException
+ */
+ public void createCoreConfiguration(String coreName, final String coreProgram) throws IOException, LMFClientException {
+ createCoreConfiguration(coreName, new ByteArrayInputStream(coreProgram.getBytes("utf-8")));
+ }
+
+
+ /**
+ * Update the core configuration for the given core using the LDPath program passed as argument.
+ *
+ * Note that this library provides no further functionality for evaluating LDPath programs. You may use the
+ * separate LDPath libraries at http://code.google.com/p/ldpath/.
+ *
+ * @param coreName the name of the core to update
+ * @param coreProgram InputStream providing the LDPath program to use as core configuration
+ * @throws IOException
+ * @throws LMFClientException
+ */
+ public void createCoreConfiguration(String coreName, final InputStream coreProgram) throws IOException, LMFClientException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ String serviceUrl = config.getLmfUri() + URL_CORES_SERVICE + "/" + URLEncoder.encode(coreName,"utf-8");
+
+ HttpPost post = new HttpPost(serviceUrl);
+ post.setHeader("Content-Type", "text/plain");
+ ContentProducer cp = new ContentProducer() {
+ @Override
+ public void writeTo(OutputStream outstream) throws IOException {
+ ByteStreams.copy(coreProgram,outstream);
+ }
+ };
+ post.setEntity(new EntityTemplate(cp));
+
+ try {
+
+ HttpResponse response = httpClient.execute(post);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("core {} updated successfully",coreName);
+ break;
+ default:
+ log.error("error updating core {}: {} {}",new Object[] {coreName,response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ throw new LMFClientException("error updating core "+coreName+": "+response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
+ }
+
+ } finally {
+ post.releaseConnection();
+ }
+ }
+
+
+ /**
+ * Set/update the core configuration for the given core using the LDPath program passed as argument.
+ *
+ * Note that this library provides no further functionality for evaluating LDPath programs. You may use the
+ * separate LDPath libraries at http://code.google.com/p/ldpath/.
+ *
+ * @param coreName the name of the core to update
+ * @param coreProgram the LDPath program to use as core configuration
+ * @throws IOException
+ * @throws LMFClientException
+ */
+ public void updateCoreConfiguration(String coreName, final String coreProgram) throws IOException, LMFClientException {
+ updateCoreConfiguration(coreName,new ByteArrayInputStream(coreProgram.getBytes("utf-8")));
+ }
+
+ /**
+ * Update the core configuration for the given core using the LDPath program passed as argument.
+ *
+ * Note that this library provides no further functionality for evaluating LDPath programs. You may use the
+ * separate LDPath libraries at http://code.google.com/p/ldpath/.
+ *
+ * @param coreName the name of the core to update
+ * @param coreProgram InputStream providing the LDPath program to use as core configuration
+ * @throws IOException
+ * @throws LMFClientException
+ */
+ public void updateCoreConfiguration(String coreName, final InputStream coreProgram) throws IOException, LMFClientException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ String serviceUrl = config.getLmfUri() + URL_CORES_SERVICE + "/" + URLEncoder.encode(coreName,"utf-8");
+
+ HttpPut put = new HttpPut(serviceUrl);
+ put.setHeader("Content-Type", "text/plain");
+ ContentProducer cp = new ContentProducer() {
+ @Override
+ public void writeTo(OutputStream outstream) throws IOException {
+ ByteStreams.copy(coreProgram,outstream);
+ }
+ };
+ put.setEntity(new EntityTemplate(cp));
+
+ try {
+
+ HttpResponse response = httpClient.execute(put);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("core {} updated successfully",coreName);
+ break;
+ default:
+ log.error("error updating core {}: {} {}",new Object[] {coreName,response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ throw new LMFClientException("error updating core "+coreName+": "+response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
+ }
+
+ } finally {
+ put.releaseConnection();
+ }
+ }
+
+
+ /**
+ * Remove the core with the name passed as argument.
+ *
+ * @param coreName name of the core to delete
+ * @throws IOException
+ * @throws NotFoundException in case the core with this name does not exist
+ * @throws LMFClientException
+ */
+ public void deleteCore(String coreName) throws IOException, LMFClientException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ String serviceUrl = config.getLmfUri() + URL_CORES_SERVICE + "/" + URLEncoder.encode(coreName,"utf-8");
+
+ HttpDelete delete = new HttpDelete(serviceUrl);
+
+ try {
+
+ HttpResponse response = httpClient.execute(delete);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("core {} deleted successfully",coreName);
+ break;
+ case 404:
+ log.error("core {} does not exist and could not be deleted", coreName);
+ throw new NotFoundException("core "+coreName+" does not exist and could not be deleted");
+ default:
+ log.error("error deleting core {}: {} {}",new Object[] {coreName,response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ throw new LMFClientException("error updating core "+coreName+": "+response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
+ }
+
+ } finally {
+ delete.releaseConnection();
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/c32963d5/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/ImportClient.java
----------------------------------------------------------------------
diff --git a/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/ImportClient.java b/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/ImportClient.java
new file mode 100644
index 0000000..e389e5d
--- /dev/null
+++ b/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/ImportClient.java
@@ -0,0 +1,173 @@
+/**
+ * Copyright (C) 2013 Salzburg Research.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package at.newmedialab.lmf.client.clients;
+
+import at.newmedialab.lmf.client.ClientConfiguration;
+import at.newmedialab.lmf.client.exception.LMFClientException;
+import at.newmedialab.lmf.client.util.HTTPUtil;
+import com.google.common.io.ByteStreams;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.ResponseHandler;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.ContentProducer;
+import org.apache.http.entity.EntityTemplate;
+import org.apache.http.util.EntityUtils;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.codehaus.jackson.type.TypeReference;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * This client class provides support for importing ontologies in various formats into the Linked Media Framework.
+ *
+ * Author: Sebastian Schaffert
+ */
+public class ImportClient {
+
+ private static Logger log = LoggerFactory.getLogger(ImportClient.class);
+
+ private static final String URL_TYPES_SERVICE = "/import/types";
+ private static final String URL_UPLOAD_SERVICE = "/import/upload";
+
+ private ClientConfiguration config;
+
+ private Set<String> acceptableTypes;
+
+ public ImportClient(ClientConfiguration config) {
+ this.acceptableTypes = new HashSet<String>();
+ this.config = config;
+ try {
+ this.acceptableTypes = getSupportedTypes();
+ } catch (IOException e) {
+ log.error("I/O Exception while trying to retrieve supported types",e);
+ } catch (LMFClientException e) {
+ log.error("Client Exception while trying to retrieve supported types",e);
+ }
+ }
+
+ /**
+ * Return a set of mime types representing the types that are accepted by the LMF server.
+ *
+ * @return
+ * @throws IOException
+ * @throws LMFClientException
+ */
+ public Set<String> getSupportedTypes() throws IOException, LMFClientException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ String serviceUrl = config.getLmfUri() + URL_TYPES_SERVICE;
+
+ HttpGet get = new HttpGet(serviceUrl);
+ get.setHeader("Accept", "application/json");
+
+ try {
+ HttpResponse response = httpClient.execute(get);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("list of import types retrieved successfully");
+ ObjectMapper mapper = new ObjectMapper();
+ Set<String> result =
+ mapper.readValue(response.getEntity().getContent(),new TypeReference<Set<String>>(){});
+ return result;
+ default:
+ log.error("error retrieving list of import types: {} {}",new Object[] {response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ throw new LMFClientException("error retrieving list of import types: "+response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
+ }
+
+ } finally {
+ get.releaseConnection();
+ }
+ }
+
+ /**
+ * Upload/Import a dataset in the LMF Server. The dataset is given as an Inputstream that contains data of the
+ * mime type passed as argument. The mime type must be one of the acceptable types of the server.
+ *
+ * @param in InputStream to read the dataset from; will be consumed by this method
+ * @param mimeType mime type of the input data
+ * @throws IOException
+ * @throws LMFClientException
+ */
+ public void uploadDataset(final InputStream in, final String mimeType) throws IOException, LMFClientException {
+ //Preconditions.checkArgument(acceptableTypes.contains(mimeType));
+
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ HttpPost post = HTTPUtil.createPost(URL_UPLOAD_SERVICE, config);
+ post.setHeader("Content-Type", mimeType);
+
+ ContentProducer cp = new ContentProducer() {
+ @Override
+ public void writeTo(OutputStream outstream) throws IOException {
+ ByteStreams.copy(in,outstream);
+ }
+ };
+ post.setEntity(new EntityTemplate(cp));
+
+ ResponseHandler<Boolean> handler = new ResponseHandler<Boolean>() {
+ @Override
+ public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
+ EntityUtils.consume(response.getEntity());
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("dataset uploaded updated successfully");
+ return true;
+ case 412:
+ log.error("mime type {} not acceptable by import service",mimeType);
+ return false;
+ default:
+ log.error("error uploading dataset: {} {}",new Object[] {response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ return false;
+ }
+ }
+ };
+
+ try {
+ httpClient.execute(post, handler);
+ } catch(IOException ex) {
+ post.abort();
+ throw ex;
+ } finally {
+ post.releaseConnection();
+ }
+
+ }
+
+ /**
+ * Upload the data contained in the string using the given mime type; convenience method wrapping the generic
+ * InputStream-based method.
+ *
+ * @param data
+ * @param mimeType
+ * @throws IOException
+ * @throws LMFClientException
+ */
+ public void uploadDataset(String data, String mimeType) throws IOException, LMFClientException {
+ uploadDataset(new ByteArrayInputStream(data.getBytes("utf-8")), mimeType);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/c32963d5/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/LDPathClient.java
----------------------------------------------------------------------
diff --git a/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/LDPathClient.java b/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/LDPathClient.java
new file mode 100644
index 0000000..c581e9f
--- /dev/null
+++ b/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/LDPathClient.java
@@ -0,0 +1,164 @@
+/**
+ * Copyright (C) 2013 Salzburg Research.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package at.newmedialab.lmf.client.clients;
+
+import at.newmedialab.lmf.client.ClientConfiguration;
+import at.newmedialab.lmf.client.exception.ContentFormatException;
+import at.newmedialab.lmf.client.exception.LMFClientException;
+import at.newmedialab.lmf.client.exception.NotFoundException;
+import at.newmedialab.lmf.client.model.rdf.RDFNode;
+import at.newmedialab.lmf.client.util.HTTPUtil;
+import at.newmedialab.lmf.client.util.RDFJSONParser;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpGet;
+import org.codehaus.jackson.JsonParser;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.codehaus.jackson.type.TypeReference;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.net.URLEncoder;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Add file description here!
+ * <p/>
+ * Author: Sebastian Schaffert
+ */
+public class LDPathClient {
+
+ private static Logger log = LoggerFactory.getLogger(LDPathClient.class);
+
+ private static final String URL_PATH_SERVICE = "/ldpath/path";
+ private static final String URL_PROGRAM_SERVICE = "/ldpath/program";
+
+
+ private ClientConfiguration config;
+
+ public LDPathClient(ClientConfiguration config) {
+ this.config = config;
+ }
+
+
+ /**
+ * Evaluate the path query passed as second argument, starting at the resource with the uri given as first argument.
+ * Returns a List of RDFNode objects.
+ *
+ *
+ * @param uri the uri of the resource where to start the path evaluation
+ * @param path the path to evaluate
+ * @return a list of RDFNodes representing the result of the path evaluation as returned by the server
+ * @throws LMFClientException
+ * @throws IOException
+ */
+ public List<RDFNode> evaluatePath(String uri, String path) throws LMFClientException, IOException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ String serviceUrl = config.getLmfUri() + URL_PATH_SERVICE + "?path=" + URLEncoder.encode(path, "utf-8")
+ + "&uri=" + URLEncoder.encode(uri, "utf-8");
+
+ HttpGet get = new HttpGet(serviceUrl);
+ get.setHeader("Accept", "application/json");
+
+ try {
+
+ HttpResponse response = httpClient.execute(get);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("LDPath Path Query {} evaluated successfully",path);
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
+ List<Map<String,String>> serverResult =
+ mapper.readValue(response.getEntity().getContent(),new TypeReference<List<Map<String,String>>>(){});
+
+
+ List<RDFNode> result = new ArrayList<RDFNode>();
+ for(Map<String,String> value : serverResult) {
+ result.add(RDFJSONParser.parseRDFJSONNode(value));
+ }
+ return result;
+ case 400:
+ log.error("the server did not accept the uri ({}) or path ({}) arguments",uri,path);
+ throw new ContentFormatException("the server did not accept the uri ("+uri+") or path ("+path+") arguments");
+ case 404:
+ log.error("the resource with URI {} does not exist on the server",uri);
+ throw new NotFoundException("the resource with URI "+uri+" does not exist on the server");
+ default:
+ log.error("error evaluating LDPath Path Query {}: {} {}",new Object[] {path,response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ throw new LMFClientException("error evaluating LDPath Path Query "+path+": "+response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
+ }
+
+ } finally {
+ get.releaseConnection();
+ }
+
+ }
+
+
+ public Map<String,List<RDFNode>> evaluateProgram(String uri, String program) throws LMFClientException, IOException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ String serviceUrl = config.getLmfUri() + URL_PROGRAM_SERVICE + "?program=" + URLEncoder.encode(program, "utf-8")
+ + "&uri=" + URLEncoder.encode(uri, "utf-8");
+
+ HttpGet get = new HttpGet(serviceUrl);
+ get.setHeader("Accept", "application/json");
+
+ try {
+
+ HttpResponse response = httpClient.execute(get);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("LDPath Program Query evaluated successfully:\n{}",program);
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
+ Map<String,List<Map<String,String>>> serverResult =
+ mapper.readValue(response.getEntity().getContent(),new TypeReference<Map<String,List<Map<String,String>>>>(){});
+
+
+ Map<String,List<RDFNode>> result = new HashMap<String, List<RDFNode>>();
+ for(Map.Entry<String,List<Map<String,String>>> field : serverResult.entrySet()) {
+ List<RDFNode> row = new ArrayList<RDFNode>();
+ for(Map<String,String> node : field.getValue()) {
+ row.add(RDFJSONParser.parseRDFJSONNode(node));
+ }
+ result.put(field.getKey(),row);
+ }
+ return result;
+ case 400:
+ log.error("the server did not accept the uri ({}) or program ({}) arguments",uri,program);
+ throw new ContentFormatException("the server did not accept the uri ("+uri+") or program ("+program+") arguments");
+ case 404:
+ log.error("the resource with URI {} does not exist on the server",uri);
+ throw new NotFoundException("the resource with URI "+uri+" does not exist on the server");
+ default:
+ log.error("error evaluating LDPath Program Query: {} {}",new Object[] {response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ throw new LMFClientException("error evaluating LDPath Program Query: "+response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
+ }
+
+ } finally {
+ get.releaseConnection();
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/c32963d5/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/ResourceClient.java
----------------------------------------------------------------------
diff --git a/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/ResourceClient.java b/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/ResourceClient.java
new file mode 100644
index 0000000..616be9d
--- /dev/null
+++ b/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/ResourceClient.java
@@ -0,0 +1,372 @@
+/**
+ * Copyright (C) 2013 Salzburg Research.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package at.newmedialab.lmf.client.clients;
+
+import at.newmedialab.lmf.client.ClientConfiguration;
+import at.newmedialab.lmf.client.exception.ContentFormatException;
+import at.newmedialab.lmf.client.exception.LMFClientException;
+import at.newmedialab.lmf.client.exception.NotFoundException;
+import at.newmedialab.lmf.client.model.content.Content;
+import at.newmedialab.lmf.client.model.content.StreamContent;
+import at.newmedialab.lmf.client.model.meta.Metadata;
+import at.newmedialab.lmf.client.util.HTTPUtil;
+import at.newmedialab.lmf.client.util.RDFJSONParser;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.io.ByteStreams;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.ResponseHandler;
+import org.apache.http.client.methods.HttpDelete;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpOptions;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpPut;
+import org.apache.http.entity.ContentProducer;
+import org.apache.http.entity.EntityTemplate;
+import org.apache.http.util.EntityUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.util.Map;
+
+/**
+ * Add file description here!
+ * <p/>
+ * Author: Sebastian Schaffert
+ */
+public class ResourceClient {
+
+ private static Logger log = LoggerFactory.getLogger(ResourceClient.class);
+
+ private static final String URL_RESOURCE_SERVICE = "/resource";
+
+ private ClientConfiguration config;
+
+ public ResourceClient(ClientConfiguration config) {
+ this.config = config;
+
+ }
+
+ /**
+ * Create a resource in the remote LMF installation
+ * @param uri
+ * @return
+ * @throws IOException
+ */
+ public boolean createResource(String uri) throws IOException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ HttpPost post = new HttpPost(getServiceUrl(uri));
+
+ try {
+
+ HttpResponse response = httpClient.execute(post);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("resource {} already existed, not creating new",uri);
+ return true;
+ case 201:
+ log.debug("resource {} created",uri);
+ return true;
+ default:
+ log.error("error creating resource {}: {} {}",new Object[] {uri,response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ return true;
+ }
+
+ } catch (UnsupportedEncodingException e) {
+ log.error("could not encode URI parameter",e);
+ return false;
+ } finally {
+ post.releaseConnection();
+ }
+ }
+
+ /**
+ * Test whether the resource with the provided URI exists.
+ * <p/>
+ * Uses an OPTIONS call to the resource web service to determine whether the resource exists or not
+ *
+ * @param uri
+ * @return
+ * @throws IOException
+ */
+ public boolean existsResource(String uri) throws IOException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ HttpOptions options = new HttpOptions(getServiceUrl(uri));
+
+ try {
+
+ HttpResponse response = httpClient.execute(options);
+
+ if(response.containsHeader("Access-Control-Allow-Methods") && response.getFirstHeader("Access-Control-Allow-Methods").getValue().equals("POST")) {
+ return false;
+ } else if(response.containsHeader("Access-Control-Allow-Methods") && response.getFirstHeader("Access-Control-Allow-Methods").getValue().contains("GET")) {
+ return true;
+ } else {
+ log.warn("OPTIONS response did not contain a access-control-allow-methods header");
+ return false;
+ }
+
+ } catch (UnsupportedEncodingException e) {
+ log.error("could not encode URI parameter",e);
+ return false;
+ } finally {
+ options.releaseConnection();
+ }
+ }
+
+ /**
+ * Return the resource metadata for the resource with the given URI, if it exists. Returns null if the
+ * resource exists but there is no metadata. Throws an exception if the resource does not exist or some
+ * other error code was returned.
+ *
+ * @param uri
+ * @return
+ * @throws IOException
+ * @throws LMFClientException
+ */
+ public Metadata getResourceMetadata(String uri) throws IOException, LMFClientException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ HttpGet get = new HttpGet(getServiceUrl(uri));
+ get.setHeader("Accept", "application/rdf+json; rel=meta");
+
+ try {
+
+ HttpResponse response = httpClient.execute(get);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("metadata for resource {} retrieved",uri);
+ Map<String,Metadata> result = RDFJSONParser.parseRDFJSON(response.getEntity().getContent());
+ if(result.containsKey(uri)) {
+ return result.get(uri);
+ } else {
+ return null;
+ }
+ case 406:
+ log.error("server does not support metadata type application/json for resource {}, cannot retrieve", uri);
+ throw new ContentFormatException("server does not support metadata type application/json for resource "+uri);
+ case 404:
+ log.error("resource {} does not exist, cannot retrieve", uri);
+ throw new NotFoundException("resource "+uri+" does not exist, cannot retrieve");
+ default:
+ log.error("error retrieving resource {}: {} {}",new Object[] {uri,response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ throw new LMFClientException("error retrieving resource "+uri+": "+response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
+ }
+
+ } catch (UnsupportedEncodingException e) {
+ log.error("could not encode URI parameter",e);
+ throw new LMFClientException("could not encode URI parameter");
+ } finally {
+ get.releaseConnection();
+ }
+ }
+
+ /**
+ * Update (overwrite) the metadata of the resource identified by the given uri. The metadata will be serialised to
+ * application/json and sent to the Linked Media Framework server. The given metadata will override any metadata
+ * for the resource already existing on the server. The resource has to exist or be created before updating, otherwise
+ * the method will throw a NotFoundException.
+ *
+ * @param uri the URI of the resource to update
+ * @param metadata the metadata to upload to the resource
+ * @throws IOException
+ * @throws LMFClientException
+ */
+ public void updateResourceMetadata(final String uri, final Metadata metadata) throws IOException, LMFClientException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ HttpPut put = new HttpPut(getServiceUrl(uri));
+ put.setHeader("Content-Type", "application/rdf+json; rel=meta");
+ ContentProducer cp = new ContentProducer() {
+ @Override
+ public void writeTo(OutputStream outstream) throws IOException {
+ RDFJSONParser.serializeRDFJSON(ImmutableMap.of(uri, metadata), outstream);
+ }
+ };
+ put.setEntity(new EntityTemplate(cp));
+
+ try {
+
+ HttpResponse response = httpClient.execute(put);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("metadata for resource {} updated",uri);
+ break;
+ case 415:
+ log.error("server does not support metadata type application/json for resource {}, cannot update", uri);
+ throw new ContentFormatException("server does not support metadata type application/json for resource "+uri);
+ case 404:
+ log.error("resource {} does not exist, cannot update", uri);
+ throw new NotFoundException("resource "+uri+" does not exist, cannot update");
+ default:
+ log.error("error updating resource {}: {} {}",new Object[] {uri,response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ throw new LMFClientException("error updating resource "+uri+": "+response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
+ }
+
+ } catch (UnsupportedEncodingException e) {
+ log.error("could not encode URI parameter",e);
+ throw new LMFClientException("could not encode URI parameter");
+ } finally {
+ put.releaseConnection();
+ }
+ }
+
+ /**
+ * Retrieve the (human-readable) content of the given mimeType of the given resource. Will return a content
+ * object that allows reading the input stream. In case no content of the given mime type exists for the resource,
+ * will throw a ContentFormatException.
+ *
+ * @param uri
+ * @param mimeType
+ * @return
+ * @throws IOException
+ * @throws LMFClientException
+ */
+ public Content getResourceContent(String uri, String mimeType) throws IOException, LMFClientException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ HttpGet get = new HttpGet(getServiceUrl(uri));
+ get.setHeader("Accept", mimeType+"; rel=content");
+
+ try {
+
+ HttpResponse response = httpClient.execute(get);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("metadata for resource {} retrieved",uri);
+ Content content = new StreamContent(response.getEntity().getContent(),response.getEntity().getContentType().getValue(),response.getEntity().getContentLength());
+ return content;
+ case 406:
+ log.error("server does not offer content type {} for resource {}, cannot retrieve", mimeType, uri);
+ throw new ContentFormatException("server does not offer content type "+mimeType+" for resource "+uri);
+ case 404:
+ log.error("resource {} does not exist, cannot retrieve content", uri);
+ throw new NotFoundException("resource "+uri+" does not exist, cannot retrieve");
+ default:
+ log.error("error retrieving resource {}: {} {}",new Object[] {uri,response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ throw new LMFClientException("error retrieving resource "+uri+": "+response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
+ }
+
+ } catch (UnsupportedEncodingException e) {
+ log.error("could not encode URI parameter",e);
+ throw new LMFClientException("could not encode URI parameter");
+ } finally {
+ get.releaseConnection();
+ }
+ }
+
+ /**
+ * Update the content of the resource identified by the URI given as argument. The resource has to exist before
+ * content can be uploaded to it. Any existing content will be overridden. The stream of the content object
+ * will be consumed by this method. Throws ContentFormatException if the content type is not supported,
+ * NotFoundException if the resource does not exist.
+ * @param uri
+ * @param content
+ * @throws IOException
+ * @throws LMFClientException
+ */
+ public void updateResourceContent(final String uri, final Content content) throws IOException, LMFClientException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ HttpPut put = new HttpPut(getServiceUrl(uri));
+ put.setHeader("Content-Type", content.getMimeType()+"; rel=content");
+ ContentProducer cp = new ContentProducer() {
+ @Override
+ public void writeTo(OutputStream outstream) throws IOException {
+ ByteStreams.copy(content.getStream(),outstream);
+ }
+ };
+ put.setEntity(new EntityTemplate(cp));
+
+ ResponseHandler<Boolean> handler = new ResponseHandler<Boolean>() {
+ @Override
+ public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
+ EntityUtils.consume(response.getEntity());
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("content for resource {} updated",uri);
+ return true;
+ case 406:
+ log.error("server does not support content type {} for resource {}, cannot update", content.getMimeType(),uri);
+ return false;
+ case 404:
+ log.error("resource {} does not exist, cannot update", uri);
+ return false;
+ default:
+ log.error("error updating resource {}: {} {}",new Object[] {uri,response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ return false;
+ }
+ }
+ };
+
+ try {
+ httpClient.execute(put, handler);
+ } catch(IOException ex) {
+ put.abort();
+ throw ex;
+ } finally {
+ put.releaseConnection();
+ }
+
+ }
+
+
+ public void deleteResource(String uri) throws IOException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ HttpDelete delete = new HttpDelete(getServiceUrl(uri));
+
+ try {
+
+ HttpResponse response = httpClient.execute(delete);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("resource {} deleted",uri);
+ break;
+ case 400:
+ log.error("resource {} invalid, cannot delete", uri);
+ break;
+ case 404:
+ log.error("resource {} does not exist, cannot delete", uri);
+ break;
+ default:
+ log.error("error deleting resource {}: {} {}",new Object[] {uri,response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ }
+
+ } catch (UnsupportedEncodingException e) {
+ log.error("could not encode URI parameter",e);
+ } finally {
+ delete.releaseConnection();
+ }
+ }
+
+ private String getServiceUrl(String uri) throws UnsupportedEncodingException {
+ return config.getLmfUri() + URL_RESOURCE_SERVICE + "?uri=" + URLEncoder.encode(uri,"utf-8");
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-marmotta/blob/c32963d5/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/SPARQLClient.java
----------------------------------------------------------------------
diff --git a/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/SPARQLClient.java b/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/SPARQLClient.java
new file mode 100644
index 0000000..4524928
--- /dev/null
+++ b/lmf-client/lmf-client-java/src/main/java/at/newmedialab/lmf/client/clients/SPARQLClient.java
@@ -0,0 +1,227 @@
+/**
+ * Copyright (C) 2013 Salzburg Research.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package at.newmedialab.lmf.client.clients;
+
+import at.newmedialab.lmf.client.ClientConfiguration;
+import at.newmedialab.lmf.client.exception.LMFClientException;
+import at.newmedialab.lmf.client.model.rdf.BNode;
+import at.newmedialab.lmf.client.model.rdf.Literal;
+import at.newmedialab.lmf.client.model.rdf.RDFNode;
+import at.newmedialab.lmf.client.model.rdf.URI;
+import at.newmedialab.lmf.client.model.sparql.SPARQLResult;
+import at.newmedialab.lmf.client.util.HTTPUtil;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpGet;
+import org.codehaus.jackson.JsonParser;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.codehaus.jackson.type.TypeReference;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.net.URLEncoder;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Add file description here!
+ * <p/>
+ * Author: Sebastian Schaffert
+ */
+public class SPARQLClient {
+
+ private static Logger log = LoggerFactory.getLogger(SPARQLClient.class);
+
+ private static final String URL_QUERY_SERVICE = "/sparql/select";
+ private static final String URL_UPDATE_SERVICE = "/sparql/update";
+
+ private ClientConfiguration config;
+
+ public SPARQLClient(ClientConfiguration config) {
+ this.config = config;
+ }
+
+ /**
+ * Run a SPARQL Select query against the LMF Server and return the results as SPARQL Result. Results will be
+ * transfered and parsed using the SPARQL JSON format.
+ * @param query a SPARQL Select query to run on the database
+ * @return
+ * @throws IOException
+ * @throws LMFClientException
+ */
+ @SuppressWarnings("unchecked")
+ public SPARQLResult select(String query) throws IOException, LMFClientException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ String serviceUrl = config.getLmfUri() + URL_QUERY_SERVICE + "?query=" + URLEncoder.encode(query, "utf-8");
+
+ HttpGet get = new HttpGet(serviceUrl);
+ get.setHeader("Accept", "application/sparql-results+json");
+
+ try {
+
+ HttpResponse response = httpClient.execute(get);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("SPARQL Query {} evaluated successfully",query);
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
+ Map<String,Map<String,List<?>>> resultMap =
+ mapper.readValue(response.getEntity().getContent(),new TypeReference<Map<String,Map<String,List<?>>>>(){});
+
+ if(resultMap.isEmpty()) {
+ return null;
+ } else {
+ List<?> head = resultMap.get("head").get("vars");
+ Set<String> fieldNames = new HashSet<String>();
+ for(Object o : head) {
+ if(o instanceof String) {
+ fieldNames.add((String)o);
+ }
+ }
+
+ SPARQLResult result = new SPARQLResult(fieldNames);
+
+ List<?> bindings = resultMap.get("results").get("bindings");
+ for(Object o : bindings) {
+ if(o instanceof Map) {
+ Map<String,RDFNode> row = new HashMap<String, RDFNode>();
+ for(Map.Entry<String,?> entry : ((Map<String,?>)o).entrySet()) {
+ Map<String,String> nodeDef = (Map<String,String>) entry.getValue();
+ RDFNode node = null;
+ if("uri".equalsIgnoreCase(nodeDef.get("type"))) {
+ node = new URI(nodeDef.get("value"));
+ } else if("literal".equalsIgnoreCase(nodeDef.get("type")) ||
+ "typed-literal".equalsIgnoreCase(nodeDef.get("type"))) {
+ String lang = nodeDef.get("xml:lang");
+ String datatype = nodeDef.get("datatype");
+
+ if(lang != null) {
+ node = new Literal(nodeDef.get("value"),lang);
+ } else if(datatype != null) {
+ node = new Literal(nodeDef.get("value"),new URI(datatype));
+ } else {
+ node = new Literal(nodeDef.get("value"));
+ }
+ } else if("bnode".equalsIgnoreCase(nodeDef.get("type"))) {
+ node = new BNode(nodeDef.get("value"));
+ } else {
+ log.error("unknown result node type: {}",nodeDef.get("type"));
+ }
+
+ if(node != null) {
+ row.put(entry.getKey(),node);
+ }
+ }
+ result.add(row);
+ }
+ }
+ return result;
+ }
+ default:
+ log.error("error evaluating SPARQL Select Query {}: {} {}",new Object[] {query,response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ throw new LMFClientException("error evaluating SPARQL Select Query "+query+": "+response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
+ }
+
+ } finally {
+ get.releaseConnection();
+ }
+ }
+
+ /**
+ * Carry out a SPARQL ASK Query and return either true or false, depending on the query result.
+ *
+ * @param askQuery
+ * @return
+ * @throws IOException
+ * @throws LMFClientException
+ */
+ public boolean ask(String askQuery) throws IOException, LMFClientException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ String serviceUrl = config.getLmfUri() + URL_QUERY_SERVICE + "?query=" + URLEncoder.encode(askQuery, "utf-8");
+
+ HttpGet get = new HttpGet(serviceUrl);
+ get.setHeader("Accept", "application/sparql-results+json");
+
+ try {
+
+ HttpResponse response = httpClient.execute(get);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("SPARQL ASK Query {} evaluated successfully",askQuery);
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
+ Map<String,Object> resultMap =
+ mapper.readValue(response.getEntity().getContent(),new TypeReference<Map<String,Object>>(){});
+
+ if(resultMap.isEmpty()) {
+ return false;
+ } else {
+ Boolean result = resultMap.get("boolean") != null && ((String)resultMap.get("boolean")).equalsIgnoreCase("true");
+ return result;
+ }
+ default:
+ log.error("error evaluating SPARQL ASK Query {}: {} {}",new Object[] {askQuery,response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ throw new LMFClientException("error evaluating SPARQL ASK Query "+askQuery+": "+response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
+ }
+
+ } finally {
+ get.releaseConnection();
+ }
+ }
+
+ /**
+ * Execute a SPARQL Update query according to the SPARQL 1.1 standard. The query will only be passed to the server,
+ * which will react either with ok (in this the method simply returns) or with error (in this case, the method
+ * throws an LMFClientException).
+ *
+ * @param updateQuery the SPARQL Update 1.1 query string
+ * @throws IOException in case a connection problem occurs
+ * @throws LMFClientException in case the server returned and error and did not execute the update
+ */
+ public void update(String updateQuery) throws IOException, LMFClientException {
+ HttpClient httpClient = HTTPUtil.createClient(config);
+
+ String serviceUrl = config.getLmfUri() + URL_UPDATE_SERVICE + "?update=" + URLEncoder.encode(updateQuery, "utf-8");
+
+ HttpGet get = new HttpGet(serviceUrl);
+
+ try {
+
+ HttpResponse response = httpClient.execute(get);
+
+ switch(response.getStatusLine().getStatusCode()) {
+ case 200:
+ log.debug("SPARQL UPDATE Query {} evaluated successfully",updateQuery);
+ break;
+ default:
+ log.error("error evaluating SPARQL UPDATE Query {}: {} {}",new Object[] {updateQuery,response.getStatusLine().getStatusCode(),response.getStatusLine().getReasonPhrase()});
+ throw new LMFClientException("error evaluating SPARQL UPDATE Query "+updateQuery +": "+response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
+ }
+
+ } finally {
+ get.releaseConnection();
+ }
+ }
+
+}