org.apache.jena.atlas.io.IndentedWriter Java Examples

The following examples show how to use org.apache.jena.atlas.io.IndentedWriter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StreamingRDFWriter.java    From tarql with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void writeTurtle(String baseIRI, PrefixMapping prefixes, boolean writeBase) {
	// Auto-register RDF prefix so that rdf:type is displayed well
	// All other prefixes come from the query and should be as author intended
	prefixes = ensureRDFPrefix(prefixes);

	if (writeBase) {
		// Jena's streaming Turtle writers don't output base even if it is provided,
		// so we write it directly.
		IndentedWriter w = new IndentedWriter(out);
		RiotLib.writeBase(w, baseIRI);
		w.flush();
	}
	
	StreamRDF writer = new WriterStreamRDFBlocks(out);
	if (dedupWindowSize > 0) {
		writer = new StreamRDFDedup(writer, dedupWindowSize);
	}
	writer.start();
	writer.base(baseIRI);
	for (Entry<String, String> e : prefixes.getNsPrefixMap().entrySet()) {
		writer.prefix(e.getKey(), e.getValue());
	}
	StreamOps.sendTriplesToStream(triples, writer);
	writer.finish();
}
 
Example #2
Source File: SPARQLExtQuerySerializer.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
private static void outputValuesOneRow(IndentedWriter out, List<Var> variables, Binding row, SerializationContext cxt) {
    // A value may be null for UNDEF
    for (Var var : variables) {
        out.print(" ");
        Node value = row.get(var);
        if (value == null) {
            out.print("UNDEF");
        } else {
            // Context for bnodes.
            // Bnodes don't occur in legal syntax but a rewritten query may
            // have them.  The output will not be legal SPARQL.
            // ARQ (SPARQL with extensions) does parse blankd nodes in VALUES. 
            SPARQLExtFmtUtils.printNode(out, value, cxt);
        }
    }
}
 
Example #3
Source File: SHACLCWriter.java    From shacl with Apache License 2.0 6 votes vote down vote up
private void writeImports(IndentedWriter out, Resource ontology) {
	List<Resource> imports = JenaUtil.getResourceProperties(ontology, OWL.imports);
	Collections.sort(imports, new Comparator<Resource>() {
		@Override
		public int compare(Resource o1, Resource o2) {
			return o1.getURI().compareTo(o2.getURI());
		}
		
	});
	if(!imports.isEmpty()) {
		for(Resource imp : imports) {
			out.println("IMPORTS <" + imp.getURI() + ">");
		}
		out.println();
	}
}
 
Example #4
Source File: SHACLCWriter.java    From shacl with Apache License 2.0 6 votes vote down vote up
private void writeShapes(IndentedWriter out, Model model) {
	
	List<Resource> shapes = new LinkedList<>();
	for(Resource shape : JenaUtil.getAllInstances(SH.NodeShape.inModel(model))) {
		if(shape.isURIResource()) {
			shapes.add(shape);
		}
	}
	// Collections.sort(shapes, ResourceComparator.get());
	
	for(int i = 0; i < shapes.size(); i++) {
		if(i > 0) {
			out.println();
		}
		writeShape(out, shapes.get(i));
	}
}
 
Example #5
Source File: TemplatePlan.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
public void exec(List<Var> variables, List<Binding> values, Context context) {
	final IndentedWriter writer = ContextUtils.getTemplateOutput(context);
	boolean first = true;
	final FunctionEnv env = new FunctionEnvBase(context);
	String result;
	for(Iterator<Binding> it=values.iterator(); it.hasNext();) {
		Binding binding = it.next();
		if (first && before != null) {
			result = getExprEval(before, binding, context, env);
			writer.print(result);
		}
		if (!first && separator != null) {
			result = getExprEval(separator, binding, context, env);
			writer.print(result);
		}
		result = getExprEval(expr, binding, context, env);
		writer.print(result);
		first = false;
		if (!it.hasNext() && after != null) {
			result = getExprEval(after, binding, context, env);
			writer.print(result);
		}
		writer.flush();
	}
}
 
Example #6
Source File: SHACLCWriter.java    From shacl with Apache License 2.0 6 votes vote down vote up
private void writeExtraStatements(IndentedWriter out, Resource subject, Set<Property> specialProperties, boolean wrapped) {
	List<Statement> extras = getExtraStatements(subject, specialProperties);
	if(!extras.isEmpty()) {
		if(wrapped) {
			out.print("( ");
		}
		for(Statement s : extras) {
			out.print(" " + getPredicateName(s.getPredicate()));
			out.print("=");
			out.print(node(s.getObject()));
		}
		if(wrapped) {
			out.print(" )");
		}
	}
}
 
Example #7
Source File: ST_Decr.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
public NodeValue exec(Binding binding, ExprList args, String uri, FunctionEnv env) {
    if (args == null) {
        throw new ARQInternalErrorException("FunctionBase: Null args list");
    }
    if (args.size() != 0) {
        throw new ExprEvalException("Expecting zero argument");
    }
    IndentedWriter writer = ContextUtils.getTemplateOutput(env.getContext());
    if(writer != null) {
    	writer.decIndent();
    } else {
    	LOG.warn("calling st:decr() outside TEMPLATE context.");
    }
    return EMPTY_NODE;
}
 
Example #8
Source File: ST_Incr.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
public NodeValue exec(Binding binding, ExprList args, String uri, FunctionEnv env) {
    if (args == null) {
        throw new ARQInternalErrorException("FunctionBase: Null args list");
    }
    if (args.size() != 0) {
        throw new ExprEvalException("Expecting zero argument");
    }
    IndentedWriter writer = ContextUtils.getTemplateOutput(env.getContext());
    if(writer != null) {
    	writer.incIndent();
    } else {
    	LOG.warn("calling st:incr() outside TEMPLATE context.");
    }
    return EMPTY_NODE;
}
 
Example #9
Source File: S_JSON.java    From rdf-delta with Apache License 2.0 6 votes vote down vote up
public static void json(HttpServletRequest req, HttpServletResponse resp, JsonValue responseContent) {
    try { 
        resp.setHeader(HttpNames.hCacheControl, "no-cache");
        resp.setHeader(HttpNames.hContentType,  WebContent.contentTypeJSON);
        resp.setStatus(HttpSC.OK_200);
        try(ServletOutputStream out = resp.getOutputStream(); IndentedWriter b = new IndentedWriter(out); ) {
            b.setFlatMode(true);
            JSON.write(b, responseContent);
            b.ensureStartOfLine();
            b.flush();
            out.write('\n');
        }
    } catch (IOException ex) {
        LOG.warn("json: IOException", ex);
        try { 
            resp.sendError(HttpSC.INTERNAL_SERVER_ERROR_500, "Internal server error");
        } catch (IOException ex2) {}
    }
}
 
Example #10
Source File: tarql.java    From tarql with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void processResults(TarqlQueryExecution ex) throws IOException {
	if (testQuery && ex.getFirstQuery().getConstructTemplate() != null) {
		IndentedWriter out = new IndentedWriter(System.out); 
		new FmtTemplate(out, new SerializationContext(ex.getFirstQuery())).format(ex.getFirstQuery().getConstructTemplate());
		out.flush();
	}
	if (ex.getFirstQuery().isSelectType()) {
		System.out.println(ResultSetFormatter.asText(ex.execSelect()));
	} else if (ex.getFirstQuery().isAskType()) {
		System.out.println(ResultSetFormatter.asText(ex.execSelect()));
	} else if (ex.getFirstQuery().isConstructType()) {
		resultTripleIterator = resultTripleIterator.andThen(ex.execTriples());
	} else {
		cmdError("Only query forms CONSTRUCT, SELECT and ASK are supported");
	}
}
 
Example #11
Source File: SPARQLExtFmtExprSPARQL.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
public SPARQLGenerateFmtExprARQVisitor(IndentedWriter writer, SerializationContext cxt) {
	out = writer;
	if (cxt == null) {
		context = new SerializationContext();
	} else {
		context = cxt;
	}
}
 
Example #12
Source File: SHACLCWriter.java    From shacl with Apache License 2.0 5 votes vote down vote up
private void writeNestedShapes(IndentedWriter out, Resource subject) {
	for(Resource node : JenaUtil.getResourceProperties(subject, SH.node)) {
		if(node.isAnon()) {
			writeShapeBody(out, node);
		}
	}
}
 
Example #13
Source File: SPARQLExtFmtUtils.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
public static void printTriple(IndentedWriter out, Triple triple, SerializationContext sCxt) {
    printNode(out, triple.getSubject(), sCxt);
    out.print(" ");
    printNode(out, triple.getPredicate(), sCxt);
    out.print(" ");
    printNode(out, triple.getObject(), sCxt);
}
 
Example #14
Source File: SPARQLExtFmtUtils.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
public static void fmtSPARQL(IndentedWriter iOut, ExprList exprs, SerializationContext pmap) {
    SPARQLExtFmtExprSPARQL fmt = new SPARQLExtFmtExprSPARQL(iOut, pmap);
    String sep = "";
    for (Expr expr : exprs) {
        iOut.print(sep);
        sep = " , ";
        fmt.format(expr);
    }
}
 
Example #15
Source File: SPARQLExtQuerySerializer.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
public SPARQLExtQuerySerializer(IndentedWriter out, SerializationContext context) {
    this.out = out;
    this.context = context;
    this.fmtTemplate = new SPARQLExtFormatterTemplate(out, context);
    this.fmtExpr = new SPARQLExtFmtExprSPARQL(out, context);
    this.fmtElement = new SPARQLExtFormatterElement(out, context);
}
 
Example #16
Source File: SPARQLExtFmtUtils.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
public static void formatPattern(IndentedWriter out, BasicPattern pattern, SerializationContext sCxt) {
    boolean first = true;
    for (Triple triple : pattern) {
        if (!first) {
            out.print("\n");
        }
        printTriple(out, triple, sCxt);
        out.print(" .");
        first = false;
    }
}
 
Example #17
Source File: SPARQLExtQuerySerializer.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
void appendVarList(Query query, IndentedWriter sb, List<String> vars) {
    boolean first = true;
    for (String varName : vars) {
        Var var = Var.alloc(varName);
        if (!first) {
            sb.print(" ");
        }
        sb.print(var.toString());
        first = false;
    }

}
 
Example #18
Source File: SPARQLExtQuerySerializer.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
static void appendURIList(Query query, IndentedWriter sb, List<Node> vars) {
    SerializationContext cxt = new SerializationContext(query);
    boolean first = true;
    for (Node node : vars) {
        if (!first) {
            sb.print(" ");
        }
        SPARQLExtFmtUtils.printNode(sb, node, cxt);
        first = false;
    }
}
 
Example #19
Source File: SHACLCWriter.java    From shacl with Apache License 2.0 5 votes vote down vote up
@Override
public void write(Writer out, Graph graph, PrefixMap prefixMap, String baseURI, Context context) {
       IndentedWriter iOut = RiotLib.create(out);
       iOut.setUnitIndent(1);
       iOut.setPadChar('\t');
	write(iOut, graph, prefixMap, baseURI, context);
}
 
Example #20
Source File: SHACLCWriter.java    From shacl with Apache License 2.0 5 votes vote down vote up
@Override
public void write(OutputStream out, Graph graph, PrefixMap prefixMap, String baseURI, Context context) {
       IndentedWriter iOut = new IndentedWriter(out);
       iOut.setUnitIndent(1);
       iOut.setPadChar('\t');
	write(iOut, graph, prefixMap, baseURI, context);
}
 
Example #21
Source File: SHACLCWriter.java    From shacl with Apache License 2.0 5 votes vote down vote up
private void write(IndentedWriter out, Graph graph, PrefixMap prefixMap, String baseURI, Context context) {
	Model model = ModelFactory.createModelForGraph(graph);
	if(baseURI != null) {
		out.println("BASE <" + baseURI + ">");
		out.println();
	}
	writeImports(out, model.getResource(baseURI));
	writePrefixes(out, prefixMap);
	writeShapes(out, model);
	out.flush();
}
 
Example #22
Source File: StreamingRDFWriter.java    From tarql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void writeNTriples() {
	StreamRDF writer = new WriterStreamRDFPlain(new IndentedWriter(out));
	if (dedupWindowSize > 0) {
		writer = new StreamRDFDedup(writer, dedupWindowSize);
	}
	writer.start();
	StreamOps.sendTriplesToStream(triples, writer);
	writer.finish();
}
 
Example #23
Source File: SHACLCWriter.java    From shacl with Apache License 2.0 5 votes vote down vote up
private void writePrefixes(IndentedWriter out, PrefixMap prefixMap) {
	List<String> prefixes = new LinkedList<String>(prefixMap.getMapping().keySet());
	if(!prefixes.isEmpty()) {
		Collections.sort(prefixes);
		for(String prefix : prefixes) {
			if(SHACLC.getDefaultPrefixURI(prefix) == null) {
				out.println("PREFIX " + prefix + ": <" + prefixMap.expand(prefix + ":") + ">");
			}
		}
		out.println();
	}
}
 
Example #24
Source File: ExQuerySelect2.java    From xcurator with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args)
{
    // Create the data.
    // This wil be the background (unnamed) graph in the dataset.
    Model model = createModel() ;
    
    // First part or the query string 
    String prolog = "PREFIX dc: <"+DC.getURI()+">" ;
    
    // Query string.
    String queryString = prolog + NL +
        "SELECT ?title WHERE {?x dc:title ?title}" ; 
    
    Query query = QueryFactory.create(queryString) ;
    // Print with line numbers
    query.serialize(new IndentedWriter(System.out,true)) ;
    System.out.println() ;
    
    // Create a single execution of this query, apply to a model
    // which is wrapped up as a Dataset
    
    // Or QueryExecutionFactory.create(queryString, model) ;        
    try(QueryExecution qexec = QueryExecutionFactory.create(query, model)) {
        // A ResultSet is an iterator - any query solutions returned by .next()
        // are not accessible again.
        // Create a ResultSetRewindable that can be reset to the beginning.
        // Do before first use.
        
        ResultSetRewindable rewindable = ResultSetFactory.makeRewindable(qexec.execSelect()) ;
        ResultSetFormatter.out(rewindable) ;
        rewindable.reset() ;
        ResultSetFormatter.out(rewindable) ;
    }
}
 
Example #25
Source File: SHACLCWriter.java    From shacl with Apache License 2.0 5 votes vote down vote up
private void writeProperty(IndentedWriter out, Resource property) {
	out.print(getPathString(property));
	out.print(" ");
	
	out.print(getPropertyTypes(property));
	
	// Count block
	out.print(" ");
	out.print("[");
	Statement minCountS = property.getProperty(SH.minCount);
	if(minCountS != null) {
		out.print("" + minCountS.getInt());
	}
	else {
		out.print("0");
	}
	out.print("..");
	Statement maxCountS = property.getProperty(SH.maxCount);
	if(maxCountS != null) {
		out.print("" + maxCountS.getInt());
	}
	else {
		out.print("*");
	}
	out.print("]");
	
	writeExtraStatements(out, property, specialPropertyProperties, false);
	
	writeNestedShapes(out, property);
	
	out.println(" .");
}
 
Example #26
Source File: ExRIOT_out3.java    From xcurator with Apache License 2.0 5 votes vote down vote up
@Override
public void write(Writer out, Graph graph, PrefixMap prefixMap, String baseURI, Context context)
{
    // Writers are discouraged : just hope the charset is UTF-8.
    IndentedWriter x = RiotLib.create(out) ;
    SSE.write(x, graph) ;
}
 
Example #27
Source File: RDFStar2RDF.java    From RDFstarTools with Apache License 2.0 5 votes vote down vote up
public void execute()
{
    // print all prefixes and the base IRI to the output file
    try ( IndentedWriter writer = new IndentedWriter(outStream) ) {
        RiotLib.writePrefixes(writer, pmap);
        RiotLib.writeBase(writer, baseIRI);

        // second pass over the file to perform the conversion in a streaming manner
        final PipedRDFIterator<Triple> it = new PipedRDFIterator<>(BUFFER_SIZE);
        final PipedTriplesStream triplesStream = new PipedTriplesStream(it);

        // PipedRDFStream and PipedRDFIterator need to be on different threads
        final Runnable r = new Runnable() {
            @Override
            public void run() {
                RDFParser.create().labelToNode( LabelToNode.createUseLabelEncoded() )
                .source(inputFilename)
                .lang(LangTurtleStar.TURTLESTAR)
                .base(baseIRI)
                .build()
                .parse(triplesStream);
            }
        };
        final ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(r);

        final NodeFormatter nFmt = new NodeFormatterTTL(baseIRI, pmap);

        while ( it.hasNext() ) {
            printTriples(it.next(), writer, nFmt, false);
        }

        it.close();
        executor.shutdown();

        writer.write(" .");
        writer.flush();
    }
}
 
Example #28
Source File: SPARQLExtFormatterBase.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
protected String slotToString(Node n) {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try (IndentedWriter w = new IndentedWriter(os)) {
        SPARQLExtFmtUtils.printNode(w, n, context);
    }
    return new String(os.toByteArray(), Charset.defaultCharset());

}
 
Example #29
Source File: PHandlerSPARQLUpdateOutput.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Patch patch) {
    IndentedWriter x = new IndentedWriter(System.out) ;
    x.setLineNumbers(true);
    x.setLinePrefix("GSP>> ");
    RDFChanges scData = new RDFChangesWriteUpdate(x) ;
    patch.play(scData);
    x.flush();
}
 
Example #30
Source File: JSONX.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
/** Write out a JSON value - pass a JSON Object to get legal exchangeable JSON */
private static void writeFlat(OutputStream output, JsonValue jValue) {
    IndentedWriter iOut = new IndentedWriter(output) ;
    iOut.setFlatMode(true);
    JSON.write(iOut, jValue) ;
    iOut.flush() ;
}