protected DataPropertyStatement fillDataPropertyStatementWithJenaLiteral(
     DataPropertyStatement dataPropertyStatement, Literal l) {
   dataPropertyStatement.setData(l.getLexicalForm());
   dataPropertyStatement.setDatatypeURI(l.getDatatypeURI());
   dataPropertyStatement.setLanguage(l.getLanguage());
   return dataPropertyStatement;
 }
Ejemplo n.º 2
0
  public static Method create(QuerySolution qs) throws Exception {
    Resource id = (Resource) qs.get("x");
    Literal fullPath = (Literal) qs.get("fullPath");
    Literal name = (Literal) qs.get("name");
    Literal accessModifier = (Literal) qs.get("accessModifier");
    Literal lineStart = (Literal) qs.get("line_start");
    Literal lineEnd = (Literal) qs.get("line_end");
    Resource returnType = (Resource) qs.get("returnType");
    Resource hasParameter = (Resource) qs.get("hasParameter");
    Resource throwsException = (Resource) qs.get("throwsException");
    Resource belongsTo = (Resource) qs.get("belongsTo");

    Method meth = new Method(id.toString(), name.getValue().toString());
    meth.setAccessModifier(accessModifier.getValue().toString());
    meth.setFullPath(fullPath.getValue().toString());
    meth.setLineStart(lineStart.getInt());
    meth.setLineEnd(lineEnd.getInt());
    meth.setReturnType(returnType.toString());
    if (hasParameter != null) {
      meth.setHasParameter(hasParameter.toString());
    }
    if (throwsException != null) {
      meth.setThrowsException(throwsException.toString());
    }
    meth.setBelongsTo(belongsTo.toString());

    return meth;
  }
  /**
   * Query SPARQL endpoint with a SELECT query
   *
   * @param qExec QueryExecution encapsulating the query
   * @return model retrieved by querying the endpoint
   */
  private Model getSelectModel(QueryExecution qExec) {
    Model model = ModelFactory.createDefaultModel();
    Graph graph = model.getGraph();
    ResultSet results = qExec.execSelect();

    while (results.hasNext()) {
      QuerySolution sol = results.next();
      String subject;
      String predicate;
      RDFNode object;

      try {
        subject = sol.getResource("s").toString();
        predicate = sol.getResource("p").toString();
        object = sol.get("o");
      } catch (NoSuchElementException e) {
        logger.error("SELECT query does not return a (?s ?p ?o) Triple");
        continue;
      }

      Node objNode;
      if (object.isLiteral()) {
        Literal obj = object.asLiteral();
        objNode = NodeFactory.createLiteral(obj.getString(), obj.getDatatype());
      } else {
        objNode = NodeFactory.createLiteral(object.toString());
      }

      graph.add(
          new Triple(NodeFactory.createURI(subject), NodeFactory.createURI(predicate), objNode));
    }

    return model;
  }
 /**
  * Converts a JENA API Literal object into an OWL API OWLLiteral object.
  *
  * @param lit
  * @return
  */
 protected OWLLiteral convertLiteral(Literal lit) {
   String datatypeURI = lit.getDatatypeURI();
   OWLLiteral owlLiteral;
   if (datatypeURI == null) { // rdf:PlainLiteral
     owlLiteral = df.getOWLLiteral(lit.getLexicalForm(), lit.getLanguage());
   } else {
     owlLiteral =
         df.getOWLLiteral(lit.getLexicalForm(), df.getOWLDatatype(IRI.create(datatypeURI)));
   }
   return owlLiteral;
 }
 private URL getURL(Literal literalURL) {
   URL url = null;
   try {
     url = new URL(literalURL.getString());
   } catch (Exception e) {
     e.printStackTrace();
   }
   return url;
 }
Ejemplo n.º 6
0
 public int[] getSourceColumns(Resource resource) {
   if (_model.contains(resource, Vertere.source_column)) {
     Statement sourceColumn = _model.getProperty(resource, Vertere.source_column);
     return new int[] {sourceColumn.getInt()};
   } else if (_model.contains(resource, Vertere.source_columns)) {
     Statement sourceColumns = _model.getProperty(resource, Vertere.source_columns);
     Resource listResource = sourceColumns.getResource();
     RDFList list = listResource.as(RDFList.class);
     List<RDFNode> javalist = list.asJavaList();
     int[] sourceColumnNumbers = new int[javalist.size()];
     for (int i = 0; i < javalist.size(); i++) {
       RDFNode node = javalist.get(i);
       Literal value = node.asLiteral();
       sourceColumnNumbers[i] = value.getInt();
     }
     return sourceColumnNumbers;
   } else {
     return new int[0];
   }
 }
Ejemplo n.º 7
0
  @Test
  public void shouldSortTriplesForDisplay() {
    final Model model = createDefaultModel();

    model.setNsPrefix("prefix", "namespace");
    final Property propertyA = model.createProperty("namespace", "a");
    final Property propertyB = model.createProperty("namespace", "b");
    final Property propertyC = model.createProperty("c");
    final Literal literalA = model.createLiteral("a");
    final Literal literalB = model.createLiteral("b");
    final Resource resourceB = model.createResource("b");
    model.add(resourceB, propertyA, literalA);

    final Resource a = model.createResource("a");
    model.add(a, propertyC, literalA);

    model.add(a, propertyB, literalA);

    model.add(a, propertyA, literalA);
    model.add(a, propertyA, literalB);

    final Iterator<Quad> iterator = DatasetFactory.create(model).asDatasetGraph().find();

    final List<Quad> sortedTriples = testObj.getSortedTriples(model, iterator);

    sortedTriples.get(0).matches(ANY, a.asNode(), propertyA.asNode(), literalA.asNode());
    sortedTriples.get(1).matches(ANY, a.asNode(), propertyA.asNode(), literalB.asNode());
    sortedTriples.get(2).matches(ANY, a.asNode(), propertyB.asNode(), literalA.asNode());
    sortedTriples.get(3).matches(ANY, a.asNode(), propertyC.asNode(), literalA.asNode());
    sortedTriples.get(4).matches(ANY, resourceB.asNode(), propertyC.asNode(), literalA.asNode());
  }
Ejemplo n.º 8
0
  private boolean checkAlreadyAgreed() {
    //		System.err.println(license);
    if (license.exists() && user != null && !user.equals("")) {
      try {
        model.read(new FileInputStream(license), null);

        QueryExecution qexec = QueryExecutionFactory.create(queryString, model);
        try {
          ResultSet results = qexec.execSelect();
          while (results.hasNext()) {
            QuerySolution soln = results.nextSolution();
            try {
              Literal u = soln.getLiteral("user");
              //							System.err.println("user: "******"software");
              //							System.err.println("software: "+s);
              Calendar d = ((XSDDateTime) soln.getLiteral("date").getValue()).asCalendar();
              //							System.err.println("date: "+d);

              if (u.getString().equals(user)
                  && s.getString().equals(software)
                  && d.before(Calendar.getInstance())) {
                return true;
              }
            } catch (JenaException e) {
              // ignore
            } catch (ClassCastException e) {
              System.err.println(e.getMessage());
            }
          }
        } finally {
          qexec.close();
        }

      } catch (FileNotFoundException e) {
      }
    }
    return false;
  }
Ejemplo n.º 9
0
 public void doCleanLiterals(Model model) {
   Model retractionsModel = ModelFactory.createDefaultModel();
   Model additionsModel = ModelFactory.createDefaultModel();
   model.enterCriticalSection(Lock.WRITE);
   try {
     ClosableIterator<Statement> closeIt = model.listStatements();
     try {
       for (Iterator<Statement> stmtIt = closeIt; stmtIt.hasNext(); ) {
         Statement stmt = stmtIt.next();
         if (stmt.getObject().isLiteral()) {
           Literal lit = (Literal) stmt.getObject();
           String lex = lit.getLexicalForm();
           char[] chars = lex.toCharArray();
           char[] cleanChars = new char[chars.length];
           int cleanPos = 0;
           boolean badChar = false;
           for (int i = 0; i < chars.length; i++) {
             if (java.lang.Character.getNumericValue(chars[i]) > 31
                 && java.lang.Character.isDefined(chars[i])) {
               cleanChars[cleanPos] = chars[i];
               cleanPos++;
             } else {
               log.error("Bad char in " + lex);
               log.error("Numeric value " + java.lang.Character.getNumericValue(chars[i]));
               badChar = true;
             }
           }
           String cleanLex = new String(cleanChars);
           if (badChar) {
             retractionsModel.add(stmt);
             Literal newLit = null;
             if (lit.getLanguage() != null && lit.getLanguage().length() > 0) {
               newLit = additionsModel.createLiteral(cleanLex, lit.getLanguage());
             } else if (lit.getDatatype() != null) {
               newLit = additionsModel.createTypedLiteral(cleanLex, lit.getDatatype());
             } else {
               newLit = additionsModel.createLiteral(cleanLex);
             }
             additionsModel.add(stmt.getSubject(), stmt.getPredicate(), newLit);
           }
         }
       }
     } finally {
       closeIt.close();
     }
     model.remove(retractionsModel);
     model.add(additionsModel);
     log.debug("Cleaned " + additionsModel.size() + " literals");
   } finally {
     model.leaveCriticalSection();
   }
 }
Ejemplo n.º 10
0
  public void teste() {
    // String name = this.getName();
    String title = "";
    String service = "http://dblp.rkbexplorer.com/sparql";
    String query =
        "PREFIX akt:  <http://www.aktors.org/ontology/portal#> "
            + "PREFIX akt:  <http://www.aktors.org/ontology/portal#> "
            + " SELECT DISTINCT ?name ?title "
            + " WHERE "
            + " { "
            + " ?auth akt:full-name "
            + "\""
            + nameAuthorField
            + "\""
            + " . "
            + " ?pub a akt:Publication-Reference ;"
            + " akt:has-title ?title ;"
            + " akt:has-author ?auth ."
            + " } ";
    QueryExecution queryExecution = QueryExecutionFactory.sparqlService(service, query);
    try {
      ResultSet results = queryExecution.execSelect();
      while (results.hasNext()) {
        QuerySolution querySolution = results.nextSolution();
        // consume title
        Literal literal = querySolution.getLiteral("title");
        title = ("" + literal.getValue());

        // add titulo a lista tituloPublicacao
        this.tituloPublicacao.add(title);
      }
    } catch (QueryExceptionHTTP e) {
      System.out.println(service + " is DOWN");
    } finally {
      queryExecution.close();
    }
  }
Ejemplo n.º 11
0
 @Test
 public void testInfoStamp() {
   String versionString = "E3.14159", commentString = "gloopSmurfale";
   String resourceString =
       "_x eye:assumed 'ABC'; _x eye:checked 'DEF'; _x eye:version '%v'; _x eye:comment '%c'"
           .replaceAll("%v", versionString)
           .replaceAll("%c", commentString);
   InfoStamp i = new InfoStamp(resourceInModel(resourceString));
   Calendar now = Calendar.getInstance();
   Resource root = i.stamp(now);
   Model stamp = root.getModel();
   Literal dateLiteral = ModelFactory.createDefaultModel().createTypedLiteral(now);
   String dateString = "'" + dateLiteral.getLexicalForm() + "'" + dateLiteral.getDatatypeURI();
   String expectedFormat =
       "[eye:assumed 'ABC' & eye:checked 'DEF' & eye:dated <date>"
           + " & eye:comment '<comment>' & eye:version '<version>']";
   String expectedString =
       expectedFormat
           .replaceAll("<date>", dateString)
           .replaceAll("<version>", versionString)
           .replaceAll("<comment>", commentString);
   Model expected = model(expectedString);
   assertIsoModels(expected, stamp);
 }
Ejemplo n.º 12
0
  /**
   * Create a JCR value from an RDF node with the given JCR type
   *
   * @param valueFactory
   * @param data
   * @param type
   * @return
   * @throws RepositoryException
   */
  public Value createValue(final ValueFactory valueFactory, final RDFNode data, final int type)
      throws RepositoryException {
    assert (valueFactory != null);

    if (data.isURIResource() && (type == REFERENCE || type == WEAKREFERENCE)) {
      // reference to another node (by path)
      final Node nodeFromGraphSubject =
          session.getNode(graphSubjects.getPathFromSubject(data.asResource()));
      return valueFactory.createValue(nodeFromGraphSubject, type == WEAKREFERENCE);
    } else if (data.isURIResource() || type == URI) {
      // some random opaque URI
      return valueFactory.createValue(data.toString(), PropertyType.URI);
    } else if (data.isResource()) {
      // a non-URI resource (e.g. a blank node)
      return valueFactory.createValue(data.toString(), UNDEFINED);
    } else if (data.isLiteral() && type == UNDEFINED) {
      // the JCR schema doesn't know what this should be; so introspect
      // the RDF and try to figure it out
      final Literal literal = data.asLiteral();
      final RDFDatatype dataType = literal.getDatatype();
      final Object rdfValue = literal.getValue();

      if (rdfValue instanceof Boolean) {
        return valueFactory.createValue((Boolean) rdfValue);
      } else if (rdfValue instanceof Byte
          || (dataType != null && dataType.getJavaClass() == Byte.class)) {
        return valueFactory.createValue(literal.getByte());
      } else if (rdfValue instanceof Double) {
        return valueFactory.createValue((Double) rdfValue);
      } else if (rdfValue instanceof Float) {
        return valueFactory.createValue((Float) rdfValue);
      } else if (rdfValue instanceof Long
          || (dataType != null && dataType.getJavaClass() == Long.class)) {
        return valueFactory.createValue(literal.getLong());
      } else if (rdfValue instanceof Short
          || (dataType != null && dataType.getJavaClass() == Short.class)) {
        return valueFactory.createValue(literal.getShort());
      } else if (rdfValue instanceof Integer) {
        return valueFactory.createValue((Integer) rdfValue);
      } else if (rdfValue instanceof XSDDateTime) {
        return valueFactory.createValue(((XSDDateTime) rdfValue).asCalendar());
      } else {
        return valueFactory.createValue(literal.getString(), STRING);
      }

    } else {
      LOGGER.debug("Using default JCR value creation for RDF literal: {}", data);
      return valueFactory.createValue(data.asLiteral().getString(), type);
    }
  }
Ejemplo n.º 13
0
 public String toString() {
   return literal.getString();
 }
Ejemplo n.º 14
0
  @Override
  public Model open(Assembler a, Resource root, Mode mode) {

    Resource rootModel = getUniqueResource(root, BASE_MODEL);
    if (rootModel == null) {
      throw new AssemblerException(root, String.format(NO_X_PROVIDED, BASE_MODEL, root));
    }
    Model baseModel = a.openModel(rootModel, mode);

    Literal modelName = getUniqueLiteral(root, JA.modelName);
    if (modelName == null) {
      throw new AssemblerException(root, String.format(NO_X_PROVIDED, JA.modelName, root));
    }

    Literal factoryName = getUniqueLiteral(root, EVALUATOR_FACTORY);
    if (factoryName == null) {
      throw new AssemblerException(root, String.format(NO_X_PROVIDED, EVALUATOR_FACTORY, root));
    }
    SecurityEvaluator securityEvaluator = null;
    try {
      Class<?> factoryClass = Class.forName(factoryName.getString());
      Method method = factoryClass.getMethod("getInstance");
      if (!SecurityEvaluator.class.isAssignableFrom(method.getReturnType())) {
        throw new AssemblerException(
            root,
            String.format(
                "%s (found at %s for %s) getInstance() must return an instance of SecurityEvaluator",
                factoryName, EVALUATOR_FACTORY, root));
      }
      if (!Modifier.isStatic(method.getModifiers())) {
        throw new AssemblerException(
            root,
            String.format(
                "%s (found at %s for %s) getInstance() must be a static method",
                factoryName, EVALUATOR_FACTORY, root));
      }
      securityEvaluator = (SecurityEvaluator) method.invoke(null);
    } catch (SecurityException e) {
      throw new AssemblerException(
          root, String.format(ERROR_FINDING_FACTORY, factoryName, e.getMessage()), e);
    } catch (IllegalArgumentException e) {
      throw new AssemblerException(
          root, String.format(ERROR_FINDING_FACTORY, factoryName, e.getMessage()), e);
    } catch (ClassNotFoundException e) {
      throw new AssemblerException(
          root,
          String.format(
              "Class %s (found at %s for %s) could not be loaded",
              factoryName, EVALUATOR_FACTORY, root));
    } catch (NoSuchMethodException e) {
      throw new AssemblerException(
          root,
          String.format(
              "%s (found at %s for %s) must implement a static getInstance() that returns an instance of SecurityEvaluator",
              factoryName, EVALUATOR_FACTORY, root));
    } catch (IllegalAccessException e) {
      throw new AssemblerException(
          root, String.format(ERROR_FINDING_FACTORY, factoryName, e.getMessage()), e);
    } catch (InvocationTargetException e) {
      throw new AssemblerException(
          root, String.format(ERROR_FINDING_FACTORY, factoryName, e.getMessage()), e);
    }

    return Factory.getInstance(securityEvaluator, modelName.asLiteral().getString(), baseModel);
  }
Ejemplo n.º 15
0
 /**
  * Test that two literals are semantically equivalent. In some cases this may be the sames as
  * equals, in others equals is stricter. For example, two xsd:int literals with the same value but
  * different language tag are semantically equivalent but distinguished by the java equality
  * function in order to support round tripping.
  */
 public boolean sameValueAs(Literal other) {
   return asNode().sameValueAs(other.asNode());
 }
Ejemplo n.º 16
0
 private static void doLang(StringBuffer json, Literal literal) {
   String language = literal.getLanguage();
   if (!language.equals("")) {
     json.append(", \"xml:lang\": \"" + language + "\"");
   }
 }
Ejemplo n.º 17
0
 private static void doDatatype(StringBuffer json, Literal literal) {
   String datatype = literal.getDatatypeURI();
   if (datatype != null) {
     json.append(", \"datatype\": \"" + datatype + "\"");
   }
 }
Ejemplo n.º 18
0
 public void doProcessStrings(VitroRequest vreq) {
   try {
     String className = vreq.getParameter("className");
     String methodName = vreq.getParameter("methodName");
     String propertyName = vreq.getParameter("propertyName");
     String newPropertyName = vreq.getParameter("newPropertyName");
     // for now, we'll make the destination and source models the same
     Model destination = getModel(vreq.getParameter("destinationModelName"), vreq);
     String processModel = vreq.getParameter("processModel");
     Model savedAdditionsModel = null;
     Model savedRetractionsModel = null;
     String additionsModelStr = vreq.getParameter("additionsModel");
     if ((additionsModelStr != null) && (additionsModelStr.length() > 0)) {
       savedAdditionsModel = getModel(additionsModelStr, vreq);
     }
     String retractionsModelStr = vreq.getParameter("retractionsModel");
     if ((retractionsModelStr != null) && (retractionsModelStr.length() > 0)) {
       savedRetractionsModel = getModel(retractionsModelStr, vreq);
     }
     Model additionsModel = ModelFactory.createDefaultModel();
     Model retractionsModel = ModelFactory.createDefaultModel();
     Class<?> stringProcessorClass = Class.forName(className);
     Object processor = stringProcessorClass.newInstance();
     Class<?>[] methArgs = {String.class};
     Method meth = stringProcessorClass.getMethod(methodName, methArgs);
     Property prop = ResourceFactory.createProperty(propertyName);
     Property newProp = ResourceFactory.createProperty(newPropertyName);
     destination.enterCriticalSection(Lock.READ);
     try {
       ClosableIterator<Statement> closeIt =
           destination.listStatements((Resource) null, prop, (RDFNode) null);
       for (Iterator<Statement> stmtIt = closeIt; stmtIt.hasNext(); ) {
         Statement stmt = stmtIt.next();
         if (stmt.getObject().isLiteral()) {
           Literal lit = (Literal) stmt.getObject();
           String lex = lit.getLexicalForm();
           Object[] args = {lex};
           String newLex = "";
           try {
             newLex = (String) meth.invoke(processor, args);
           } catch (InvocationTargetException e) {
             throw new RuntimeException(e);
           }
           if (!newLex.equals(lex)) {
             retractionsModel.add(stmt);
             if (newLex.length() > 0) {
               Literal newLit = null;
               if (lit.getLanguage() != null && lit.getLanguage().length() > 0) {
                 newLit = additionsModel.createLiteral(newLex, lit.getLanguage());
               } else if (lit.getDatatype() != null) {
                 newLit = additionsModel.createTypedLiteral(newLex, lit.getDatatype());
               } else {
                 newLit = additionsModel.createLiteral(newLex);
               }
               additionsModel.add(stmt.getSubject(), newProp, newLit);
             }
           }
         }
       }
       if (processModel != null) {
         destination.add(additionsModel);
         destination.remove(retractionsModel);
       }
       if (savedAdditionsModel != null) {
         savedAdditionsModel.add(additionsModel);
       }
       if (savedRetractionsModel != null) {
         savedRetractionsModel.add(retractionsModel);
       }
     } finally {
       destination.leaveCriticalSection();
     }
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
Ejemplo n.º 19
0
  private void updateModel(
      HttpServletRequest req,
      HttpServletResponse resp,
      Property[] permissions,
      ModelUpdater modelUpdater)
      throws ServletException, IOException {
    Query query = getQuery(req, resp);
    ServletContext context = getServletContext();
    if (query == null) return;

    if (performPermissionsCheck(context, query, resp, permissions)) return;

    String uri = query.getURI();

    AbstractSerializer as = serializer.get(query.getContentType());
    if (as == null || !(as instanceof JenaSerializer)) {
      resp.setStatus(
          query.negotiatedContentType()
              ? HttpServletResponse.SC_BAD_REQUEST
              : HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    Model model = ModelFactory.createDefaultModel();
    model.read(req.getInputStream(), query.getURI(), ((JenaSerializer) as).getSerialization());

    Model target = dataset.getNamedModel(uri);
    Set<Statement> before = target.listStatements().toSet();

    modelUpdater.updateModel(model, uri);

    Set<Statement> after = target.listStatements().toSet();

    Set<Statement> intersection = new HashSet<Statement>(before);
    intersection.retainAll(after);

    before.removeAll(intersection); // All those removed
    after.removeAll(intersection); // All those added

    Model changesetModel = ModelFactory.createDefaultModel();

    Resource changeset = changesetModel.createResource();
    Literal date =
        changesetModel.createTypedLiteral(
            dateFormat.format(new Date()), new BaseDatatype(XSD.date.getURI()));

    changeset
        .addProperty(Namespaces.rdf.p("type"), CS.ChangeSet)
        .addProperty(Namespaces.dc.p("date"), date)
        .addProperty(CS.subjectOfChange, changesetModel.createResource(query.getURI()))
        .addProperty(DC.creator, query.getUser());

    for (Statement statement : before)
      changeset.addProperty(Namespaces.cs.p("removal"), statement.createReifiedStatement());
    for (Statement statement : after)
      changeset.addProperty(Namespaces.cs.p("addition"), statement.createReifiedStatement());

    String filename = query.getURL().getPath() + "/" + date.getLexicalForm() + ".n3";
    File file = new File(logDirectory, filename);
    file.getParentFile().mkdirs();
    FileWriter ow = new FileWriter(new File(logDirectory.getPath(), filename));
    changesetModel.write(ow, "N3");
    ow.close();

    resp.setStatus(200);
  }