use of org.apache.rya.streams.api.exception.RyaStreamsException in project incubator-rya by apache.
the class KafkaRunQueryIT method runQuery.
@Test
public void runQuery() throws Exception {
// Setup some constant that will be used through the test.
final String ryaInstance = UUID.randomUUID().toString();
final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
// This query is completely in memory, so it doesn't need to be closed.
final QueryRepository queries = new InMemoryQueryRepository(new InMemoryQueryChangeLog(), Scheduler.newFixedRateSchedule(0L, 5, TimeUnit.SECONDS));
// Add the query to the query repository.
final StreamsQuery sQuery = queries.add("SELECT * WHERE { ?person <urn:worksAt> ?business . }", true, false);
final UUID queryId = sQuery.getQueryId();
final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);
// The thread that will run the tested interactor.
final Thread testThread = new Thread() {
@Override
public void run() {
final RunQuery runQuery = new KafkaRunQuery(kafka.getKafkaHostname(), kafka.getKafkaPort(), statementsTopic, resultsTopic, queries, new TopologyFactory());
try {
runQuery.run(queryId);
} catch (final RyaStreamsException e) {
// Do nothing. Test will still fail because the expected results will be missing.
}
}
};
// Create the topics.
kafka.createTopic(statementsTopic);
kafka.createTopic(resultsTopic);
// Create the statements that will be loaded.
final ValueFactory vf = new ValueFactoryImpl();
final List<VisibilityStatement> statements = new ArrayList<>();
statements.add(new VisibilityStatement(vf.createStatement(vf.createURI("urn:Alice"), vf.createURI("urn:worksAt"), vf.createURI("urn:BurgerJoint")), "a"));
statements.add(new VisibilityStatement(vf.createStatement(vf.createURI("urn:Bob"), vf.createURI("urn:worksAt"), vf.createURI("urn:TacoShop")), "a"));
statements.add(new VisibilityStatement(vf.createStatement(vf.createURI("urn:Charlie"), vf.createURI("urn:worksAt"), vf.createURI("urn:TacoShop")), "a"));
// Create the expected results.
final List<VisibilityBindingSet> expected = new ArrayList<>();
MapBindingSet bs = new MapBindingSet();
bs.addBinding("person", vf.createURI("urn:Alice"));
bs.addBinding("business", vf.createURI("urn:BurgerJoint"));
expected.add(new VisibilityBindingSet(bs, "a"));
bs = new MapBindingSet();
bs.addBinding("person", vf.createURI("urn:Bob"));
bs.addBinding("business", vf.createURI("urn:TacoShop"));
expected.add(new VisibilityBindingSet(bs, "a"));
bs = new MapBindingSet();
bs.addBinding("person", vf.createURI("urn:Charlie"));
bs.addBinding("business", vf.createURI("urn:TacoShop"));
expected.add(new VisibilityBindingSet(bs, "a"));
// Execute the test. This will result in a set of results that were read from the results topic.
final List<VisibilityBindingSet> results;
try {
// Wait for the program to start.
testThread.start();
Thread.sleep(2000);
// Write some statements to the program.
final LoadStatements loadStatements = new KafkaLoadStatements(statementsTopic, producer);
loadStatements.fromCollection(statements);
// Read the output of the streams program.
consumer.subscribe(Lists.newArrayList(resultsTopic));
results = KafkaTestUtil.pollForResults(500, 6, 3, consumer);
} finally {
// Tear down the test.
testThread.interrupt();
testThread.join(3000);
}
// Show the read results matched the expected ones.
assertEquals(expected, results);
}
use of org.apache.rya.streams.api.exception.RyaStreamsException in project incubator-rya by apache.
the class ListQueriesCommand method execute.
@Override
public void execute(final String[] args) throws ArgumentsException, ExecutionException {
requireNonNull(args);
// Parse the command line arguments.
final KafkaParameters params = new KafkaParameters();
try {
new JCommander(params, args);
} catch (final ParameterException e) {
throw new ArgumentsException("Could not list the queries because of invalid command line parameters.", e);
}
// Create the Kafka backed QueryChangeLog.
final String bootstrapServers = params.kafkaIP + ":" + params.kafkaPort;
final String topic = KafkaTopics.queryChangeLogTopic(params.ryaInstance);
final QueryChangeLog queryChangeLog = KafkaQueryChangeLogFactory.make(bootstrapServers, topic);
// The ListQueries command doesn't use the scheduled service feature.
final Scheduler scheduler = Scheduler.newFixedRateSchedule(0L, 5, TimeUnit.SECONDS);
final QueryRepository queryRepo = new InMemoryQueryRepository(queryChangeLog, scheduler);
// Execute the list queries command.
try {
final ListQueries listQueries = new DefaultListQueries(queryRepo);
try {
final Set<StreamsQuery> queries = listQueries.all();
System.out.println(formatQueries(queries));
} catch (final RyaStreamsException e) {
System.err.println("Unable to retrieve the queries.");
e.printStackTrace();
System.exit(1);
}
} catch (final Exception e) {
System.err.println("Problem encountered while closing the QueryRepository.");
e.printStackTrace();
System.exit(1);
}
}
use of org.apache.rya.streams.api.exception.RyaStreamsException in project incubator-rya by apache.
the class DeleteQueryCommand method execute.
@Override
public void execute(final String[] args) throws ArgumentsException, ExecutionException {
requireNonNull(args);
// Parse the command line arguments.
final RemoveParameters params = new RemoveParameters();
try {
new JCommander(params, args);
} catch (final ParameterException e) {
throw new ArgumentsException("Could not add a new query because of invalid command line parameters.", e);
}
// Create the Kafka backed QueryChangeLog.
final String bootstrapServers = params.kafkaIP + ":" + params.kafkaPort;
final String topic = KafkaTopics.queryChangeLogTopic(params.ryaInstance);
final QueryChangeLog queryChangeLog = KafkaQueryChangeLogFactory.make(bootstrapServers, topic);
// The DeleteQuery command doesn't use the scheduled service feature.
final Scheduler scheduler = Scheduler.newFixedRateSchedule(0L, 5, TimeUnit.SECONDS);
final QueryRepository queryRepo = new InMemoryQueryRepository(queryChangeLog, scheduler);
// Execute the delete query command.
try {
final DeleteQuery deleteQuery = new DefaultDeleteQuery(queryRepo);
try {
deleteQuery.delete(UUID.fromString(params.queryId));
System.out.println("Deleted query: " + params.queryId);
} catch (final RyaStreamsException e) {
System.err.println("Unable to delete query with ID: " + params.queryId);
e.printStackTrace();
System.exit(1);
}
} catch (final Exception e) {
System.err.println("Problem encountered while closing the QueryRepository.");
e.printStackTrace();
System.exit(1);
}
}
use of org.apache.rya.streams.api.exception.RyaStreamsException in project incubator-rya by apache.
the class KafkaLoadStatements method fromFile.
@Override
public void fromFile(final Path statementsPath, final String visibilities) throws RyaStreamsException {
requireNonNull(statementsPath);
requireNonNull(visibilities);
if (!statementsPath.toFile().exists()) {
throw new RyaStreamsException("Could not load statements at path '" + statementsPath + "' because that " + "does not exist. Make sure you've entered the correct path.");
}
// Create an RDF Parser whose format is derived from the statementPath's file extension.
final RDFFormat format = RDFFormat.forFileName(statementsPath.getFileName().toString());
final RDFParser parser = Rio.createParser(format);
// Set a handler that writes the statements to the specified kafka topic.
parser.setRDFHandler(new RDFHandlerBase() {
@Override
public void startRDF() throws RDFHandlerException {
log.trace("Starting loading statements.");
}
@Override
public void handleStatement(final Statement stmnt) throws RDFHandlerException {
final VisibilityStatement visiStatement = new VisibilityStatement(stmnt, visibilities);
producer.send(new ProducerRecord<>(topic, visiStatement));
}
@Override
public void endRDF() throws RDFHandlerException {
producer.flush();
log.trace("Done.");
}
});
// Do the parse and load.
try {
parser.parse(Files.newInputStream(statementsPath), "");
} catch (RDFParseException | RDFHandlerException | IOException e) {
throw new RyaStreamsException("Could not load the RDF file's Statements into Rya Streams.", e);
}
}
use of org.apache.rya.streams.api.exception.RyaStreamsException in project incubator-rya by apache.
the class KafkaRunQuery method run.
@Override
public void run(final UUID queryId) throws RyaStreamsException {
requireNonNull(queryId);
// Fetch the query from the repository. Throw an exception if it isn't present.
final Optional<StreamsQuery> query = queryRepo.get(queryId);
if (!query.isPresent()) {
throw new RyaStreamsException("Could not run the Query with ID " + queryId + " because no such query " + "is currently registered.");
}
// Build a processing topology using the SPARQL, provided statements topic, and provided results topic.
final String sparql = query.get().getSparql();
final TopologyBuilder topologyBuilder;
try {
topologyBuilder = topologyFactory.build(sparql, statementsTopic, resultsTopic, new RandomUUIDFactory());
} catch (final Exception e) {
throw new RyaStreamsException("Could not run the Query with ID " + queryId + " because a processing " + "topolgoy could not be built for the SPARQL " + sparql, e);
}
// Setup the Kafka Stream program.
final Properties streamsProps = new Properties();
streamsProps.setProperty(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaHostname + ":" + kafkaPort);
// Use the Query ID as the Application ID to ensure we resume where we left off the last time this command was run.
streamsProps.put(StreamsConfig.APPLICATION_ID_CONFIG, "KafkaRunQuery-" + queryId);
// Always start at the beginning of the input topic.
streamsProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
final KafkaStreams streams = new KafkaStreams(topologyBuilder, new StreamsConfig(streamsProps));
// If an unhandled exception is thrown, rethrow it.
streams.setUncaughtExceptionHandler((t, e) -> {
// Log the problem and kill the program.
log.error("Unhandled exception while processing the Rya Streams query. Shutting down.", e);
System.exit(1);
});
// Setup a shutdown hook that kills the streams program at shutdown.
final CountDownLatch awaitTermination = new CountDownLatch(1);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
awaitTermination.countDown();
}
});
// Run the streams program and wait for termination.
streams.start();
try {
awaitTermination.await();
} catch (final InterruptedException e) {
log.warn("Interrupted while waiting for termination. Shutting down.");
}
streams.close();
}
Aggregations