Search in sources :

Example 1 with RyaStreamsException

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);
}
Also used : InMemoryQueryChangeLog(org.apache.rya.streams.api.queries.InMemoryQueryChangeLog) VisibilityBindingSet(org.apache.rya.api.model.VisibilityBindingSet) StreamsQuery(org.apache.rya.streams.api.entity.StreamsQuery) RunQuery(org.apache.rya.streams.api.interactor.RunQuery) LoadStatements(org.apache.rya.streams.api.interactor.LoadStatements) ValueFactoryImpl(org.openrdf.model.impl.ValueFactoryImpl) ArrayList(java.util.ArrayList) TopologyFactory(org.apache.rya.streams.kafka.topology.TopologyFactory) ValueFactory(org.openrdf.model.ValueFactory) InMemoryQueryRepository(org.apache.rya.streams.api.queries.InMemoryQueryRepository) VisibilityStatement(org.apache.rya.api.model.VisibilityStatement) RyaStreamsException(org.apache.rya.streams.api.exception.RyaStreamsException) InMemoryQueryRepository(org.apache.rya.streams.api.queries.InMemoryQueryRepository) QueryRepository(org.apache.rya.streams.api.queries.QueryRepository) MapBindingSet(org.openrdf.query.impl.MapBindingSet) UUID(java.util.UUID) Test(org.junit.Test)

Example 2 with RyaStreamsException

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);
    }
}
Also used : StreamsQuery(org.apache.rya.streams.api.entity.StreamsQuery) Scheduler(com.google.common.util.concurrent.AbstractScheduledService.Scheduler) ListQueries(org.apache.rya.streams.api.interactor.ListQueries) DefaultListQueries(org.apache.rya.streams.api.interactor.defaults.DefaultListQueries) InMemoryQueryRepository(org.apache.rya.streams.api.queries.InMemoryQueryRepository) QueryChangeLog(org.apache.rya.streams.api.queries.QueryChangeLog) RyaStreamsException(org.apache.rya.streams.api.exception.RyaStreamsException) ParameterException(com.beust.jcommander.ParameterException) JCommander(com.beust.jcommander.JCommander) RyaStreamsException(org.apache.rya.streams.api.exception.RyaStreamsException) ParameterException(com.beust.jcommander.ParameterException) InMemoryQueryRepository(org.apache.rya.streams.api.queries.InMemoryQueryRepository) QueryRepository(org.apache.rya.streams.api.queries.QueryRepository) DefaultListQueries(org.apache.rya.streams.api.interactor.defaults.DefaultListQueries)

Example 3 with RyaStreamsException

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);
    }
}
Also used : Scheduler(com.google.common.util.concurrent.AbstractScheduledService.Scheduler) DefaultDeleteQuery(org.apache.rya.streams.api.interactor.defaults.DefaultDeleteQuery) InMemoryQueryRepository(org.apache.rya.streams.api.queries.InMemoryQueryRepository) QueryChangeLog(org.apache.rya.streams.api.queries.QueryChangeLog) RyaStreamsException(org.apache.rya.streams.api.exception.RyaStreamsException) ParameterException(com.beust.jcommander.ParameterException) JCommander(com.beust.jcommander.JCommander) RyaStreamsException(org.apache.rya.streams.api.exception.RyaStreamsException) ParameterException(com.beust.jcommander.ParameterException) InMemoryQueryRepository(org.apache.rya.streams.api.queries.InMemoryQueryRepository) QueryRepository(org.apache.rya.streams.api.queries.QueryRepository) DeleteQuery(org.apache.rya.streams.api.interactor.DeleteQuery) DefaultDeleteQuery(org.apache.rya.streams.api.interactor.defaults.DefaultDeleteQuery)

Example 4 with RyaStreamsException

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);
    }
}
Also used : RDFHandlerException(org.openrdf.rio.RDFHandlerException) RyaStreamsException(org.apache.rya.streams.api.exception.RyaStreamsException) Statement(org.openrdf.model.Statement) VisibilityStatement(org.apache.rya.api.model.VisibilityStatement) ProducerRecord(org.apache.kafka.clients.producer.ProducerRecord) RDFHandlerBase(org.openrdf.rio.helpers.RDFHandlerBase) IOException(java.io.IOException) RDFParser(org.openrdf.rio.RDFParser) VisibilityStatement(org.apache.rya.api.model.VisibilityStatement) RDFFormat(org.openrdf.rio.RDFFormat) RDFParseException(org.openrdf.rio.RDFParseException)

Example 5 with RyaStreamsException

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();
}
Also used : KafkaStreams(org.apache.kafka.streams.KafkaStreams) StreamsQuery(org.apache.rya.streams.api.entity.StreamsQuery) TopologyBuilder(org.apache.kafka.streams.processor.TopologyBuilder) Properties(java.util.Properties) CountDownLatch(java.util.concurrent.CountDownLatch) RyaStreamsException(org.apache.rya.streams.api.exception.RyaStreamsException) RyaStreamsException(org.apache.rya.streams.api.exception.RyaStreamsException) RandomUUIDFactory(org.apache.rya.api.function.projection.RandomUUIDFactory) StreamsConfig(org.apache.kafka.streams.StreamsConfig)

Aggregations

RyaStreamsException (org.apache.rya.streams.api.exception.RyaStreamsException)11 StreamsQuery (org.apache.rya.streams.api.entity.StreamsQuery)8 UUID (java.util.UUID)5 RyaStreamsClient (org.apache.rya.streams.api.RyaStreamsClient)5 CliCommand (org.springframework.shell.core.annotation.CliCommand)5 InMemoryQueryRepository (org.apache.rya.streams.api.queries.InMemoryQueryRepository)4 QueryRepository (org.apache.rya.streams.api.queries.QueryRepository)4 JCommander (com.beust.jcommander.JCommander)3 ParameterException (com.beust.jcommander.ParameterException)3 Scheduler (com.google.common.util.concurrent.AbstractScheduledService.Scheduler)3 IOException (java.io.IOException)3 QueryChangeLog (org.apache.rya.streams.api.queries.QueryChangeLog)3 MalformedQueryException (org.openrdf.query.MalformedQueryException)3 VisibilityStatement (org.apache.rya.api.model.VisibilityStatement)2 ArrayList (java.util.ArrayList)1 Properties (java.util.Properties)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 ProducerRecord (org.apache.kafka.clients.producer.ProducerRecord)1 KafkaStreams (org.apache.kafka.streams.KafkaStreams)1 StreamsConfig (org.apache.kafka.streams.StreamsConfig)1