Package org.openrdf.model

Examples of org.openrdf.model.Model


        String account = java.net.URI.create(resource.replaceAll(" ", "%20")).getPath().substring(1);
        String prefix = getEndpointSuffix(endpoint);
        try {
            final LdapConnection ldap = openLdapConnection(endpoint);

            Model model = new TreeModel();
            ValueFactory vf = ValueFactoryImpl.getInstance();
            String userDN = buildDN(prefix, account, ldap);

            Map<String, java.util.List<String>> accountData = getAccountData(userDN, ldap);

            final URI subject = vf.createURI(resource);
            for (String attr : MAPPING.keySet()) {
                if (!accountData.containsKey(attr)) {
                    continue;
                }

                final PredicateObjectFactory factory = MAPPING.get(attr);
                final URI predicate = factory.createPredicate(vf);

                for (String val : accountData.get(attr)) {
                    for (Value object : factory.createObjects(val, vf)) {
                        model.add(vf.createStatement(subject, predicate, object));
                    }
                }

            }
View Full Code Here


            // read triples for this entry from cache repository
            RepositoryConnection con = cacheRepository.getConnection();
            try {
                con.begin();

                Model triples = new TreeModel();
                ModelCommons.add(triples, con.getStatements(resource,null,null,true));
                ce.setTriples(triples);

                con.commit();
            } catch(RepositoryException ex) {
View Full Code Here

  @Override
  public ClientResponse retrieveResource(String resource, LDClientService client, Endpoint endpoint) throws DataRetrievalException {
        String filename = resource.substring("http://localhost/".length()) + ".ttl";

        Model triples = new TreeModel();
        try {
            ModelCommons.add(triples, DummyProvider.class.getResourceAsStream(filename), resource, RDFFormat.TURTLE);

        } catch (RDFParseException e) {
            throw new DataRetrievalException("could not parse resource data for file "+filename);
View Full Code Here

    protected void testResource(String uri, String sparqlFile) throws Exception {

        Assume.assumeTrue(ldcache.getClient().ping(uri));


        Model model = ldcache.get(valueFactory.createURI(uri));

        Assert.assertTrue(model.size() > 0);

        RepositoryConnection connection = ModelCommons.asRepository(model).getConnection();
        connection.begin();

        // run a SPARQL test to see if the returned data is correct
View Full Code Here

     * @param repository
     * @return
     * @throws RepositoryException
     */
    public static Model asModel(Repository repository, Predicate<Statement>... filters) throws RepositoryException {
        Model model = new TreeModel();

        RepositoryConnection con = repository.getConnection();
        try {
            con.begin();

View Full Code Here

    }

    @Override
    public ClientResponse retrieveResource(String resource, LDClientService client, Endpoint endpoint) throws DataRetrievalException {

        Model model = new TreeModel();

        String uri = resource;
        URI objUri;
        try {
            objUri = new URI(uri);
        } catch (URISyntaxException e) {
            throw new RuntimeException("URI '" + uri + "'could not be parsed, it is not a valid URI");
        }

        String video_id = null;
        if (uri.startsWith(YOUTUBE_V)) { // YouTube short watch video URL
            String[] p_components = objUri.getPath().split("/");
            video_id = p_components[p_components.length - 1];
        } else if (resource.startsWith(YOUTUBE_WATCH)) { // YouTube watch video URL
            List<NameValuePair> params = URLEncodedUtils.parse(objUri, "UTF-8");
            for (NameValuePair pair : params) {
                if ("v".equals(pair.getName())) {
                    video_id = pair.getValue();
                    break;
                }
            }
        } else if (uri.startsWith(YOUTUBE_GDATA)) { // GData URI
            video_id = StringUtils.removeStart(uri, YOUTUBE_GDATA);
        }
        if (StringUtils.isBlank(video_id)) {
            String msg = "Not valid video id found in '" + uri + "'";
            log.error(msg);
            throw new DataRetrievalException(msg);
        } else {
            model.add(new URIImpl(uri), new URIImpl(FOAF_PRIMARY_TOPIC), new URIImpl(YoutubeVideoProvider.YOUTUBE_BASE_URI + video_id), (Resource)null);
            // FIXME: add inverse triple, but maybe at the YoutubeVideoProvider

            ClientResponse clientResponse = new ClientResponse(200, model);
            clientResponse.setExpires(DateUtils.addYears(new Date(), 10));
            return clientResponse;
View Full Code Here

    if (wait > MAX_WAIT_TIME) {
      throw new PrimalException("wait time is not allowed to exceed " + MAX_WAIT_TIME + " seconds", 0);
    }

    final Model model = new LinkedHashModel();

    final String requestURL = createRequestURLString(topic, contentSource, minScore, maxContentCount,
        wait);

    final GetMethod method = new GetMethod(requestURL);
    try {
      configureRequest(method);
      logRequestDetails(method, requestURL);

      final int httpCode = httpClient.executeMethod(method);
      logger.debug("response code: " + httpCode);
      if (httpCode == HTTP_OK) {
        final JsonReader reader = new JsonReader(new InputStreamReader(
            method.getResponseBodyAsStream()));

        final JsonParser jsonParser = new JsonParser();
        final JsonObject responseObject = jsonParser.parse(reader).getAsJsonObject();

        logger.trace("json response string: " + responseObject.toString());

        final JsonObject responseInfo = responseObject
            .getAsJsonObject(ResponseKey.PRIMAL_RESPONSE_INFO);

        if (responseInfo != null) {
          logger.debug("processing primal response info in response");

          final Resource responseInfoId = vf.createURI(requestURL);

          ResponseValues.processIntValue(responseInfoId, PRIMAL.CONTENT_COUNT, model,
              PRIMAL.RESPONSE_INFO, responseInfo, ResponseKey.PRIMAL_CONTENT_COUNT);

          ResponseValues.processIntValue(responseInfoId, PRIMAL.TOTAL_CONCEPTS_COUNT, model,
              PRIMAL.RESPONSE_INFO, responseInfo, ResponseKey.PRIMAL_TOTAL_CONCEPTS_COUNT);

          ResponseValues.processFloatValue(responseInfoId, PRIMAL.MIN_SEMANTIC_COVERAGE, model,
              PRIMAL.RESPONSE_INFO, responseInfo, ResponseKey.PRIMAL_MIN_SEMANTIC_COVERAGE);

          ResponseValues.processStringValue(responseInfoId, PRIMAL.STATUS, model,
              PRIMAL.RESPONSE_INFO, responseInfo,
              Version.latest == getPrimalVersion() ? ResponseKey.PRIMAL_STATUS
                  : ResponseKey.PRIMAL_STATUS);

          ResponseValues.processIntValue(responseInfoId, PRIMAL.CONTENT_FILTERED_OUT, model,
              PRIMAL.RESPONSE_INFO, responseInfo, ResponseKey.PRIMAL_CONTENT_FILTERED_OUT);

          ResponseValues.processIntValue(responseInfoId, PRIMAL.CONCEPT_COUNT, model,
              PRIMAL.RESPONSE_INFO, responseInfo, ResponseKey.PRIMAL_CONCEPT_COUNT);

          ResponseValues.processFloatValue(responseInfoId, PRIMAL.HIGH_CONTENT_SCORE, model,
              PRIMAL.RESPONSE_INFO, responseInfo, ResponseKey.PRIMAL_HIGH_CONTENT_SCORE);

          ResponseValues.processFloatValue(responseInfoId, PRIMAL.TERM_COVERAGE, model,
              PRIMAL.RESPONSE_INFO, responseInfo, ResponseKey.PRIMAL_TERM_COVERAGE);

          if (responseInfo.has(ResponseKey.PRIMAL_RECOGNIZED_TERMS)) {
            final JsonArray recTerms = responseInfo.get(ResponseKey.PRIMAL_RECOGNIZED_TERMS)
                .getAsJsonArray();

            for (int i = 0; i < recTerms.size(); i++) {
              final String term = recTerms.get(i).getAsString();
              model.add(responseInfoId, PRIMAL.RECOGNIZED_TERM, vf.createLiteral(term),
                  PRIMAL.RESPONSE_INFO);
            }
          }

          ResponseValues.processStringValue(responseInfoId, PRIMAL.VIABILITY_MESSAGE, model,
              PRIMAL.RESPONSE_INFO, responseInfo, ResponseKey.PRIMAL_VIABILITY_MESSAGE);

          ResponseValues.processFloatValue(responseInfoId, PRIMAL.SEMANTIC_RATIO, model,
              PRIMAL.RESPONSE_INFO, responseInfo, ResponseKey.PRIMAL_SEMANTIC_RATIO);

          ResponseValues.processBooleanValue(responseInfoId, PRIMAL.HAS_EXPANSION, model,
              PRIMAL.RESPONSE_INFO, responseInfo, ResponseKey.PRIMAL_HAS_EXPANSION);

        }

        logger.debug("processing SKOS concepts in response");

        final JsonObject conceptScheme = responseObject
            .getAsJsonObject(ResponseKey.SKOS_CONCEPT_SCHEME);

        final JsonElement topConcepts = conceptScheme.get(ResponseKey.SKOS_HAS_TOP_CONCEPT);

        final JsonObject collection = conceptScheme.getAsJsonObject(ResponseKey.SKOS_COLLECTION);

        final Set<Entry<String, JsonElement>> members = collection.entrySet();

        final Resource conceptSchemeId = vf.createBNode();
        model.add(conceptSchemeId, RDF.TYPE, SKOS.CONCEPT_SCHEME, PRIMAL.CONCEPTS);

        final Resource collectionId = vf.createBNode();
        model.add(collectionId, RDF.TYPE, SKOS.COLLECTION, PRIMAL.CONCEPTS);

        final List<URI> rootConcepts = new ArrayList<URI>();

        if (topConcepts.isJsonArray()) {
          URI rcURI;
          final JsonArray rcArray = topConcepts.getAsJsonArray();
          for (int i = 0; i < rcArray.size(); i++) {
            rcURI = vf.createURI(rcArray.get(i).getAsString());
            rootConcepts.add(rcURI);
          }
        } else {
          final URI rcURI = vf.createURI(topConcepts.getAsString());
          rootConcepts.add(rcURI);
        }

        for (final URI rootConceptId : rootConcepts) {
          model.add(collectionId, SKOS.MEMBER, rootConceptId, PRIMAL.CONCEPTS);
          model.add(conceptSchemeId, SKOS.HAS_TOP_CONCEPT, rootConceptId, PRIMAL.CONCEPTS);

          for (final Entry<String, JsonElement> member : members) {
            final String conceptId = member.getKey();

            final JsonObject conceptAsJson = member.getValue().getAsJsonObject();

            final JsonElement prefLabelElement = conceptAsJson.get(ResponseKey.SKOS_PREF_LABEL);
            String prefLabel = null;
            if (prefLabelElement != null && !prefLabelElement.isJsonNull()) {
              prefLabel = prefLabelElement.getAsString();
            } else {
              logger.warn("no prefLabel found for {}. Skipping concept creation", conceptId);
              continue;
            }

            final URI concept = vf.createURI(conceptId);
            model.add(concept, RDF.TYPE, SKOS.CONCEPT, PRIMAL.CONCEPTS);
            model.add(concept, SKOS.PREF_LABEL, vf.createLiteral(prefLabel), PRIMAL.CONCEPTS);

            model.add(collectionId, SKOS.MEMBER, concept, PRIMAL.CONCEPTS);

            ResponseValues.processFloatValue(concept, PRIMAL.CONCEPT_SCORE, model,
                PRIMAL.CONCEPTS, conceptAsJson, ResponseKey.PRIMAL_CONCEPT_SCORE);

            ResponseValues.processStringValue(concept, SKOS.ALT_LABEL, model, PRIMAL.CONCEPTS,
                conceptAsJson, ResponseKey.SKOS_ALT_LABEL);

            ResponseValues.processStringValue(concept, PRIMAL.SOURCE, model, PRIMAL.CONCEPTS,
                conceptAsJson, ResponseKey.PRIMAL_SOURCE);

            final JsonElement narrowerElem = conceptAsJson.get(ResponseKey.SKOS_NARROWER);

            if (narrowerElem != null) {
              final JsonArray narrower = narrowerElem.getAsJsonArray();

              for (int i = 0; i < narrower.size(); i++) {
                final String narrowerId = narrower.get(i).getAsString();
                model.add(concept, SKOS.NARROWER, vf.createURI(narrowerId), PRIMAL.CONCEPTS);
              }
            }
          }
        }

        logger.debug("processing DC part of response...");
        final JsonElement dcCollection = responseObject.get(ResponseKey.DC_COLLECTION);

        if (dcCollection.isJsonArray()) {
          final JsonArray array = dcCollection.getAsJsonArray();

          logger.debug("response contains {} content items", array.size());

          for (int i = 0; i < array.size(); i++) {
            final JsonObject contentItem = array.get(i).getAsJsonObject();

            final String dcIdentifier = contentItem.get(ResponseKey.DC_IDENTIFIER).getAsString();

            final URI contentItemId = vf.createURI(dcIdentifier);
            model.add(contentItemId, RDF.TYPE, PRIMAL.CONTENT_ITEM, PRIMAL.CONTENT);

            model.add(contentItemId, DC.IDENTIFIER, vf.createLiteral(dcIdentifier),
                PRIMAL.CONTENT);

            ResponseValues.processStringValue(contentItemId, DC.TITLE, model, PRIMAL.CONTENT,
                contentItem, ResponseKey.DC_TITLE);

            ResponseValues.processStringValue(contentItemId, DC.DESCRIPTION, model,
                PRIMAL.CONTENT, contentItem, ResponseKey.DC_DESCRIPTION);

            ResponseValues.processStringValue(contentItemId, DC.PUBLISHER, model, PRIMAL.CONTENT,
                contentItem, ResponseKey.DC_PUBLISHER);

            ResponseValues.processStringValue(contentItemId, DC.SOURCE, model, PRIMAL.CONTENT,
                contentItem, ResponseKey.DC_SOURCE);

            ResponseValues.processStringValue(contentItemId, DC.RELATION, model, PRIMAL.CONTENT,
                contentItem, ResponseKey.DC_RELATION);

            ResponseValues.processDateValue(contentItemId, DC.DATE, model, PRIMAL.CONTENT,
                contentItem, ResponseKey.DC_DATE);

            ResponseValues.processFloatValue(contentItemId, PRIMAL.CONTENT_SCORE, model,
                PRIMAL.CONTENT, contentItem, ResponseKey.PRIMAL_CONTENT_SCORE);

            final JsonArray subjects = contentItem.get(ResponseKey.DC_SUBJECT).getAsJsonArray();
            for (int j = 0; j < subjects.size(); j++) {
              final String subject = subjects.get(j).getAsString();
              model.add(contentItemId, DC.SUBJECT, vf.createURI(subject), PRIMAL.CONTENT);
            }
          }

        } else {
          // TODO can this happen?
View Full Code Here

    public void testEmptyPrefixDefault() throws Exception {
        String input = "@prefix :      <http://www.example.com/resource/100/v1#> ."
                + "@prefix dc:    <http://purl.org/dc/elements/1.1/> ."
                + " :G { "
                + "  <http://www.example.com/archive/100/v1> dc:isVersionOf <http://www.example.com/resource/100>    .        }";
        Model parse = Rio.parse(new StringReader(input), "", RDFFormat.TRIG);

        StringWriter output = new StringWriter();
        Rio.write(parse, output, RDFFormat.JSONLD);

        System.out.println(output);

        Model reparse = Rio.parse(new StringReader(output.toString()), "", RDFFormat.JSONLD);

        assertTrue(ModelUtil.equals(parse, reparse));
    }
View Full Code Here

    public void testEmptyPrefixCompact() throws Exception {
        String input = "@prefix :      <http://www.example.com/resource/100/v1#> ."
                + "@prefix dc:    <http://purl.org/dc/elements/1.1/> ."
                + " :G { "
                + "  <http://www.example.com/archive/100/v1> dc:isVersionOf <http://www.example.com/resource/100>    .        }";
        Model parse = Rio.parse(new StringReader(input), "", RDFFormat.TRIG);

        WriterConfig config = new WriterConfig();
        config.set(JSONLDSettings.JSONLD_MODE, JSONLDMode.COMPACT);

        StringWriter output = new StringWriter();
        Rio.write(parse, output, RDFFormat.JSONLD, config);

        System.out.println(output);

        Model reparse = Rio.parse(new StringReader(output.toString()), "", RDFFormat.JSONLD);

        assertTrue(ModelUtil.equals(parse, reparse));
    }
View Full Code Here

        ParserConfig config = new ParserConfig();
        config.set(BasicParserSettings.FAIL_ON_UNKNOWN_DATATYPES, true);
        config.set(BasicParserSettings.FAIL_ON_UNKNOWN_LANGUAGES, true);
        rdfParser.setParserConfig(config);
        rdfParser.setValueFactory(vf);
        Model model = new LinkedHashModel();
        rdfParser.setRDFHandler(new StatementCollector(model));

        rdfParser.parse(in, "foo:bar");

        assertEquals("Unexpected number of statements, found " + model.size(), 1, model.size());

        assertTrue("missing namespaced statement", model.contains(st1));

        if (rdfParser.getRDFFormat().supportsNamespaces()) {
            assertTrue("Expected at least one namespace, found " + model.getNamespaces().size(),
                    model.getNamespaces().size() >= 1);
            assertEquals(exNs, model.getNamespace("ex").getName());
        }
    }
View Full Code Here

TOP

Related Classes of org.openrdf.model.Model

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.