You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@jena.apache.org by an...@apache.org on 2018/09/21 10:16:09 UTC
[58/70] [abbrv] jena git commit: JENA-1597: Modules jena-fuseki-main
and jena-fuseki-server
http://git-wip-us.apache.org/repos/asf/jena/blob/7e6d03af/jena-fuseki2/jena-fuseki-embedded/pom.xml
----------------------------------------------------------------------
diff --git a/jena-fuseki2/jena-fuseki-embedded/pom.xml b/jena-fuseki2/jena-fuseki-embedded/pom.xml
deleted file mode 100644
index 11f6a71..0000000
--- a/jena-fuseki2/jena-fuseki-embedded/pom.xml
+++ /dev/null
@@ -1,163 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-
- <modelVersion>4.0.0</modelVersion>
- <name>Apache Jena - Fuseki Embedded Server</name>
- <artifactId>jena-fuseki-embedded</artifactId>
-
- <parent>
- <groupId>org.apache.jena</groupId>
- <artifactId>jena-fuseki</artifactId>
- <version>3.9.0-SNAPSHOT</version>
- </parent>
-
- <packaging>jar</packaging>
-
- <properties>
- <automatic.module.name>org.apache.jena.jena-fuseki-embedded</automatic.module.name>
- </properties>
-
- <dependencies>
- <dependency>
- <groupId>org.apache.jena</groupId>
- <artifactId>jena-fuseki-core</artifactId>
- <version>3.9.0-SNAPSHOT</version>
- <!-- No specific logging - leave to the application -->
- <exclusions>
-
- <!-- No Apache Shiro - exclude to make sure it does not get accidently picked up -->
- <exclusion>
- <groupId>org.apache.shiro</groupId>
- <artifactId>shiro-core</artifactId>
- </exclusion>
- <exclusion>
- <groupId>org.apache.shiro</groupId>
- <artifactId>shiro-web</artifactId>
- </exclusion>
-
- <!-- Parts of Jena not needed but picked up via jena-fuseki-core.
- The application can put back any of these if it wants to use
- them, e.g. a text-indexed dataset, providing the version is compatible.
- -->
-
- <exclusion>
- <groupId>org.apache.jena</groupId>
- <artifactId>jena-cmds</artifactId>
- </exclusion>
- <exclusion>
- <groupId>org.apache.jena</groupId>
- <artifactId>jena-text</artifactId>
- </exclusion>
- <exclusion>
- <groupId>org.apache.jena</groupId>
- <artifactId>jena-spatial</artifactId>
- </exclusion>
- <!-- Jena use SLF4J as its API. Exclude any logging bindings picked up via Jena.
- For example, jena-fuseki-core has logging output and so some logging provider.
- For embedded use, it is the enclosing application that chooses the kind of
- logging system.
- -->
- <exclusion>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- </exclusion>
- <exclusion>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- </exclusion>
- <exclusion>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-jdk14</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
-
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- </plugin>
-
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-jar-plugin</artifactId>
- <configuration>
- <archive>
- <manifestEntries>
- <Automatic-Module-Name>${automatic.module.name}</Automatic-Module-Name>
- </manifestEntries>
- </archive>
- </configuration>
- <executions>
- <execution>
- <goals>
- <goal>test-jar</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
-
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-source-plugin</artifactId>
- <executions>
- <execution>
- <id>attach-sources</id>
- <phase>package</phase>
- <goals>
- <goal>jar-no-fork</goal>
- </goals>
- </execution>
- <execution>
- <id>attach-sources-test</id>
- <goals>
- <goal>test-jar-no-fork</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
-
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <includes>
- <include>**/TS_*.java</include>
- </includes>
- </configuration>
- </plugin>
-
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-dependency-plugin</artifactId>
- <configuration>
- <overWriteReleases>false</overWriteReleases>
- <overWriteIfNewer>true</overWriteIfNewer>
- </configuration>
- </plugin>
-
- </plugins>
-
- </build>
-
-</project>
http://git-wip-us.apache.org/repos/asf/jena/blob/7e6d03af/jena-fuseki2/jena-fuseki-embedded/src/main/java/org/apache/jena/fuseki/embedded/FusekiServer.java
----------------------------------------------------------------------
diff --git a/jena-fuseki2/jena-fuseki-embedded/src/main/java/org/apache/jena/fuseki/embedded/FusekiServer.java b/jena-fuseki2/jena-fuseki-embedded/src/main/java/org/apache/jena/fuseki/embedded/FusekiServer.java
deleted file mode 100644
index d8cc3f0..0000000
--- a/jena-fuseki2/jena-fuseki-embedded/src/main/java/org/apache/jena/fuseki/embedded/FusekiServer.java
+++ /dev/null
@@ -1,597 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.jena.fuseki.embedded;
-
-import static java.util.Objects.requireNonNull;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-
-import javax.servlet.Filter;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServlet;
-
-import org.apache.jena.atlas.lib.Pair;
-import org.apache.jena.fuseki.Fuseki;
-import org.apache.jena.fuseki.FusekiConfigException;
-import org.apache.jena.fuseki.FusekiException;
-import org.apache.jena.fuseki.build.FusekiBuilder;
-import org.apache.jena.fuseki.build.FusekiConfig;
-import org.apache.jena.fuseki.ctl.ActionPing;
-import org.apache.jena.fuseki.ctl.ActionStats;
-import org.apache.jena.fuseki.jetty.FusekiErrorHandler1;
-import org.apache.jena.fuseki.jetty.JettyLib;
-import org.apache.jena.fuseki.server.DataAccessPoint;
-import org.apache.jena.fuseki.server.DataAccessPointRegistry;
-import org.apache.jena.fuseki.server.DataService;
-import org.apache.jena.fuseki.server.FusekiVocab;
-import org.apache.jena.fuseki.server.Operation;
-import org.apache.jena.fuseki.servlets.ActionService;
-import org.apache.jena.fuseki.servlets.FusekiFilter;
-import org.apache.jena.fuseki.servlets.ServiceDispatchRegistry;
-import org.apache.jena.query.Dataset;
-import org.apache.jena.rdf.model.Model;
-import org.apache.jena.rdf.model.Resource;
-import org.apache.jena.sparql.core.DatasetGraph;
-import org.apache.jena.sparql.core.assembler.AssemblerUtils;
-import org.apache.jena.sparql.util.graph.GraphUtils;
-import org.eclipse.jetty.security.SecurityHandler;
-import org.eclipse.jetty.server.HttpConnectionFactory;
-import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.server.ServerConnector;
-import org.eclipse.jetty.servlet.DefaultServlet;
-import org.eclipse.jetty.servlet.FilterHolder;
-import org.eclipse.jetty.servlet.ServletContextHandler;
-import org.eclipse.jetty.servlet.ServletHolder;
-
-/**
- * Embedded Fuseki server. This is a Fuseki server running with a pre-configured set of
- * datasets and services. There is no admin UI and no security.
- * <p>
- * To create a embedded sever, use {@link FusekiServer} ({@link #make} is a
- * packaging of a call to {@link FusekiServer} for the case of one dataset,
- * responding to localhost only).
- * <p>
- * The application should call {@link #start()} to actually start the server
- * (it will run in the background : see {@link #join}).
- * <p>Example:
- * <pre>
- * DatasetGraph dsg = ...;
- * FusekiServer server = FusekiServer.create()
- * .port(1234)
- * .add("/ds", dsg)
- * .build();
- * server.start();
- * </pre>
- * Compact form (use the builder pattern above to get more flexibility):
- * <pre>
- * FusekiServer.make(1234, "/ds", dsg).start();
- * </pre>
- *
- */
-public class FusekiServer {
- /** Construct a Fuseki server for one dataset.
- * It only responds to localhost.
- * The returned server has not been started.
- */
- static public FusekiServer make(int port, String name, DatasetGraph dsg) {
- return create()
- .port(port)
- .loopback(true)
- .add(name, dsg)
- .build();
- }
-
- /** Return a builder, with the default choices of actions available. */
- public static Builder create() {
- return new Builder();
- }
-
- /**
- * Return a builder, with a custom set of operation-action mappings. An endpoint must
- * still be created for the server to be able to provide the action. An endpoint
- * dispatches to an operation, and an operation maps to an implementation. This is a
- * specialised operation - normal use is the operation {@link #create()}.
- */
- public static Builder create(ServiceDispatchRegistry serviceDispatchRegistry) {
- return new Builder(serviceDispatchRegistry);
- }
-
- public final Server server;
- private int port;
-
- private FusekiServer(int port, Server server) {
- this.server = server;
- // This should be the same.
- //this.port = ((ServerConnector)server.getConnectors()[0]).getPort();
- this.port = port;
- }
-
- /**
- * Return the port begin used.
- * This will be the give port, which defaults to 3330, or
- * the one actually allocated if the port was 0 ("choose a free port").
- */
- public int getPort() {
- return port;
- }
-
- /** Get the underlying Jetty server which has also been set up. */
- public Server getJettyServer() {
- return server;
- }
-
- /** Get the {@link ServletContext}.
- * Adding new servlets is possible with care.
- */
- public ServletContext getServletContext() {
- return ((ServletContextHandler)server.getHandler()).getServletContext();
- }
-
- /** Get the {@link DataAccessPointRegistry}.
- * This method is intended for inspecting the registry.
- */
- public DataAccessPointRegistry getDataAccessPointRegistry() {
- return DataAccessPointRegistry.get(getServletContext());
- }
-
- /** Get the {@link DataAccessPointRegistry}.
- * This method is intended for inspecting the registry.
- */
- public ServiceDispatchRegistry getServiceDispatchRegistry() {
- return ServiceDispatchRegistry.get(getServletContext());
- }
-
- /** Start the server - the server continues to run after this call returns.
- * To synchronise with the server stopping, call {@link #join}.
- */
- public FusekiServer start() {
- try { server.start(); }
- catch (Exception e) { throw new FusekiException(e); }
- if ( port == 0 )
- port = ((ServerConnector)server.getConnectors()[0]).getLocalPort();
- Fuseki.serverLog.info("Start Fuseki (port="+port+")");
- return this;
- }
-
- /** Stop the server. */
- public void stop() {
- Fuseki.serverLog.info("Stop Fuseki (port="+port+")");
- try { server.stop(); }
- catch (Exception e) { throw new FusekiException(e); }
- }
-
- /** Wait for the server to exit. This call is blocking. */
- public void join() {
- try { server.join(); }
- catch (Exception e) { throw new FusekiException(e); }
- }
-
- /** FusekiServer.Builder */
- public static class Builder {
- private DataAccessPointRegistry dataAccessPoints = new DataAccessPointRegistry();
- private final ServiceDispatchRegistry serviceDispatch;
- // Default values.
- private int serverPort = 3330;
- private boolean networkLoopback = false;
- private boolean verbose = false;
- private boolean withStats = false;
- private boolean withPing = false;
- // Other servlets to add.
- private List<Pair<String, HttpServlet>> servlets = new ArrayList<>();
- private List<Pair<String, Filter>> filters = new ArrayList<>();
-
- private String contextPath = "/";
- private String staticContentDir = null;
- private SecurityHandler securityHandler = null;
- private Map<String, Object> servletAttr = new HashMap<>();
-
- // Builder with standard operation-action mapping.
- Builder() {
- this.serviceDispatch = new ServiceDispatchRegistry(true);
- }
-
- // Builder with provided operation-action mapping.
- Builder(ServiceDispatchRegistry serviceDispatch) {
- // Isolate.
- this.serviceDispatch = new ServiceDispatchRegistry(serviceDispatch);
- }
-
- /** Set the port to run on.
- * @deprecated Use {@link #port}.
- */
- @Deprecated
- public Builder setPort(int port) {
- return port(port);
- }
-
- /** Set the port to run on. */
- public Builder port(int port) {
- if ( port < 0 )
- throw new IllegalArgumentException("Illegal port="+port+" : Port must be greater than or equal to zero.");
- this.serverPort = port;
- return this;
- }
-
- /** Context path to Fuseki. If it's "/" then Fuseki URL look like
- * "http://host:port/dataset/query" else "http://host:port/path/dataset/query"
- * @deprecated Use {@link #contextPath}.
- */
- @Deprecated
- public Builder setContextPath(String path) {
- return contextPath(path);
- }
-
- /** Context path to Fuseki. If it's "/" then Fuseki URL look like
- * "http://host:port/dataset/query" else "http://host:port/path/dataset/query"
- */
- public Builder contextPath(String path) {
- requireNonNull(path, "path");
- this.contextPath = path;
- return this;
- }
-
- /** Restrict the server to only responding to the localhost interface.
- * @deprecated Use {@link #networkLoopback}.
- */
- @Deprecated
- public Builder setLoopback(boolean loopback) {
- return loopback(loopback);
- }
-
- /** Restrict the server to only responding to the localhost interface. */
- public Builder loopback(boolean loopback) {
- this.networkLoopback = loopback;
- return this;
- }
-
- /** Set the location (filing system directory) to serve static file from.
- * @deprecated Use {@link #staticFileBase}.
- */
- @Deprecated
- public Builder setStaticFileBase(String directory) {
- return staticFileBase(directory);
- }
-
- /** Set the location (filing system directory) to serve static file from. */
- public Builder staticFileBase(String directory) {
- requireNonNull(directory, "directory");
- this.staticContentDir = directory;
- return this;
- }
-
- /** Set a Jetty SecurityHandler.
- * <p>
- * By default, the server runs with no security.
- * @deprecated Use {@link #staticFileBase}.
- */
- @Deprecated
- public Builder setSecurityHandler(SecurityHandler securityHandler) {
- return securityHandler(securityHandler);
- }
-
- /** Set a Jetty SecurityHandler.
- * <p>
- * By default, the server runs with no security.
- * This is more for using the basic server for testing.
- * The full Fuseki server provides security with Apache Shiro
- * and a defensive reverse proxy (e.g. Apache httpd) in front of the Jetty server
- * can also be used, which provides a wide variety of proven security options.
- */
- public Builder securityHandler(SecurityHandler securityHandler) {
- requireNonNull(securityHandler, "securityHandler");
- this.securityHandler = securityHandler;
- return this;
- }
-
- /** Set verbose logging
- * @deprecated Use {@link #verbose(boolean)}.
- */
- @Deprecated
- public Builder setVerbose(boolean verbose) {
- return verbose(verbose);
- }
-
- /** Set verbose logging */
- public Builder verbose(boolean verbose) {
- this.verbose = verbose;
- return this;
- }
-
- /** Add the "/$/stats" servlet that responds with stats about the server,
- * including counts of all calls made.
- */
- public Builder enableStats(boolean withStats) {
- this.withStats = withStats;
- return this;
- }
-
- /** Add the "/$/ping" servlet that responds to HTTP very efficiently.
- * This is useful for testing whether a server is alive, for example, from a load balancer.
- */
- public Builder enablePing(boolean withPing) {
- this.withPing = withPing;
- return this;
- }
-
- /**
- * Add the dataset with given name and a default set of services including update.
- * This is equivalent to {@code add(name, dataset, true)}.
- */
- public Builder add(String name, Dataset dataset) {
- requireNonNull(name, "name");
- requireNonNull(dataset, "dataset");
- return add(name, dataset.asDatasetGraph());
- }
-
- /**
- * Add the {@link DatasetGraph} with given name and a default set of services including update.
- * This is equivalent to {@code add(name, dataset, true)}.
- */
- /** Add the dataset with given name and a default set of services including update */
- public Builder add(String name, DatasetGraph dataset) {
- requireNonNull(name, "name");
- requireNonNull(dataset, "dataset");
- return add(name, dataset, true);
- }
-
- /**
- * Add the dataset with given name and a default set of services and enabling
- * update if allowUpdate=true.
- */
- public Builder add(String name, Dataset dataset, boolean allowUpdate) {
- requireNonNull(name, "name");
- requireNonNull(dataset, "dataset");
- return add(name, dataset.asDatasetGraph(), allowUpdate);
- }
-
- /**
- * Add the dataset with given name and a default set of services and enabling
- * update if allowUpdate=true.
- */
- public Builder add(String name, DatasetGraph dataset, boolean allowUpdate) {
- requireNonNull(name, "name");
- requireNonNull(dataset, "dataset");
- DataService dSrv = FusekiBuilder.buildDataServiceStd(dataset, allowUpdate);
- return add(name, dSrv);
- }
-
- /** Add a data service that includes dataset and service names.
- * A {@link DataService} allows for choices of the various endpoint names.
- */
- public Builder add(String name, DataService dataService) {
- requireNonNull(name, "name");
- requireNonNull(dataService, "dataService");
- return add$(name, dataService);
- }
-
- private Builder add$(String name, DataService dataService) {
- name = DataAccessPoint.canonical(name);
- if ( dataAccessPoints.isRegistered(name) )
- throw new FusekiConfigException("Data service name already registered: "+name);
- DataAccessPoint dap = new DataAccessPoint(name, dataService);
- dataAccessPoints.register(dap);
- return this;
- }
-
- /**
- * Configure using a Fuseki services/datasets assembler file.
- * <p>
- * The application is responsible for ensuring a correct classpath. For example,
- * including a dependency on {@code jena-text} if the configuration file includes
- * a text index.
- */
- public Builder parseConfigFile(String filename) {
- requireNonNull(filename, "filename");
- Model model = AssemblerUtils.readAssemblerFile(filename);
-
- // Process server context
- Resource server = GraphUtils.getResourceByType(model, FusekiVocab.tServer);
- if ( server != null )
- AssemblerUtils.setContext(server, Fuseki.getContext()) ;
-
- // Process services, whether via server ja:services or, if absent, by finding by type.
- List<DataAccessPoint> x = FusekiConfig.servicesAndDatasets(model);
- // Unbundle so that they accumulate.
- x.forEach(dap->add(dap.getName(), dap.getDataService()));
- return this;
- }
-
- /**
- * Add the given servlet with the {@code pathSpec}. These servlets are added so
- * that they are checked after the Fuseki filter for datasets and before the
- * static content handler (which is the last servlet) used for
- * {@link #setStaticFileBase(String)}.
- */
- public Builder addServlet(String pathSpec, HttpServlet servlet) {
- requireNonNull(pathSpec, "pathSpec");
- requireNonNull(servlet, "servlet");
- servlets.add(Pair.create(pathSpec, servlet));
- return this;
- }
-
- /**
- * Add a servlet attribute. Pass a value of null to remove any existing binding.
- */
- public Builder addServletAttribute(String attrName, Object value) {
- requireNonNull(attrName, "attrName");
- if ( value != null )
- servletAttr.put(attrName, value);
- else
- servletAttr.remove(attrName);
- return this;
- }
-
- /**
- * Add a filter with the pathSpec. Note that Fuseki dispatch uses a servlet filter
- * which is the last in the filter chain.
- */
- public Builder addFilter(String pathSpec, Filter filter) {
- requireNonNull(pathSpec, "pathSpec");
- requireNonNull(filter, "filter");
- filters.add(Pair.create(pathSpec, filter));
- return this;
- }
-
- /**
- * Add an operation and handler to the server. This does not enable it for any dataset.
- * <p>
- * To associate an operation with a dataset, call {@link #addOperation} after adding the dataset.
- *
- * @see #addOperation
- */
- public Builder registerOperation(Operation operation, ActionService handler) {
- registerOperation(operation, null, handler);
- return this;
- }
-
- /**
- * Add an operation to the server, together with its triggering Content-Type (may be null) and servlet handler.
- * <p>
- * To associate an operation with a dataset, call {@link #addOperation} after adding the dataset.
- *
- * @see #addOperation
- */
- public Builder registerOperation(Operation operation, String contentType, ActionService handler) {
- Objects.requireNonNull(operation, "operation");
- if ( handler == null )
- serviceDispatch.unregister(operation);
- else
- serviceDispatch.register(operation, contentType, handler);
- return this;
- }
-
- /**
- * Create an endpoint on the dataset.
- * The operation must already be registered with the builder.
- * @see #registerOperation(Operation, ActionService)
- */
- public Builder addOperation(String datasetName, String endpointName, Operation operation) {
- Objects.requireNonNull(datasetName, "datasetName");
- Objects.requireNonNull(endpointName, "endpointName");
-
- String name = DataAccessPoint.canonical(datasetName);
-
- if ( ! serviceDispatch.isRegistered(operation) )
- throw new FusekiConfigException("Operation not registered: "+operation.getName());
-
- if ( ! dataAccessPoints.isRegistered(name) )
- throw new FusekiConfigException("Dataset not registered: "+datasetName);
- DataAccessPoint dap = dataAccessPoints.get(name);
- FusekiBuilder.addServiceEP(dap.getDataService(), operation, endpointName);
- return this;
- }
-
- /**
- * Build a server according to the current description.
- */
- public FusekiServer build() {
- ServletContextHandler handler = buildFusekiContext();
- // Use HandlerCollection for several ServletContextHandlers and thus several ServletContext.
- Server server = jettyServer(serverPort, networkLoopback);
- server.setHandler(handler);
- return new FusekiServer(serverPort, server);
- }
-
- /** Build one configured Fuseki in one unit - same ServletContext, same dispatch ContextPath */
- private ServletContextHandler buildFusekiContext() {
- ServletContextHandler handler = buildServletContext(contextPath);
- ServletContext cxt = handler.getServletContext();
- Fuseki.setVerbose(cxt, verbose);
- servletAttr.forEach((n,v)->cxt.setAttribute(n, v));
- // Clone to isolate from any future changes.
- ServiceDispatchRegistry.set(cxt, new ServiceDispatchRegistry(serviceDispatch));
- DataAccessPointRegistry.set(cxt, new DataAccessPointRegistry(dataAccessPoints));
- JettyLib.setMimeTypes(handler);
- servletsAndFilters(handler);
- // Start services.
- DataAccessPointRegistry.get(cxt).forEach((name, dap)->dap.getDataService().goActive());
- return handler;
- }
-
- /** Build a ServletContextHandler */
- private ServletContextHandler buildServletContext(String contextPath) {
- if ( contextPath == null || contextPath.isEmpty() )
- contextPath = "/";
- else if ( !contextPath.startsWith("/") )
- contextPath = "/" + contextPath;
- ServletContextHandler context = new ServletContextHandler();
- context.setDisplayName(Fuseki.servletRequestLogName);
- context.setErrorHandler(new FusekiErrorHandler1());
- context.setContextPath(contextPath);
- if ( securityHandler != null )
- context.setSecurityHandler(securityHandler);
- return context;
- }
-
- /** Add servlets and servlet filters, including the {@link FusekiFilter} */
- private void servletsAndFilters(ServletContextHandler context) {
- // Fuseki dataset services filter
- // This goes as the filter at the end of any filter chaining.
- FusekiFilter ff = new FusekiFilter();
- addFilter(context, "/*", ff);
-
- if ( withStats )
- addServlet(context, "/$/stats", new ActionStats());
- if ( withPing )
- addServlet(context, "/$/ping", new ActionPing());
-
- servlets.forEach(p->addServlet(context, p.getLeft(), p.getRight()));
- filters.forEach (p-> addFilter(context, p.getLeft(), p.getRight()));
-
- if ( staticContentDir != null ) {
- DefaultServlet staticServlet = new DefaultServlet();
- ServletHolder staticContent = new ServletHolder(staticServlet);
- staticContent.setInitParameter("resourceBase", staticContentDir);
- context.addServlet(staticContent, "/");
- }
- }
-
- private static void addServlet(ServletContextHandler context, String pathspec, HttpServlet httpServlet) {
- ServletHolder sh = new ServletHolder(httpServlet);
- context.addServlet(sh, pathspec);
- }
-
- private void addFilter(ServletContextHandler context, String pathspec, Filter filter) {
- FilterHolder h = new FilterHolder(filter);
- context.addFilter(h, pathspec, null);
- }
-
- /** Jetty server with one connector/port. */
- private static Server jettyServer(int port, boolean loopback) {
- Server server = new Server();
- HttpConnectionFactory f1 = new HttpConnectionFactory();
- // Some people do try very large operations ... really, should use POST.
- f1.getHttpConfiguration().setRequestHeaderSize(512 * 1024);
- f1.getHttpConfiguration().setOutputBufferSize(1024 * 1024);
- // Do not add "Server: Jetty(....) when not a development system.
- if ( ! Fuseki.outputJettyServerHeader )
- f1.getHttpConfiguration().setSendServerVersion(false);
- ServerConnector connector = new ServerConnector(server, f1);
- connector.setPort(port);
- server.addConnector(connector);
- if ( loopback )
- connector.setHost("localhost");
- return server;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/jena/blob/7e6d03af/jena-fuseki2/jena-fuseki-embedded/src/main/java/org/apache/jena/fuseki/embedded/JettyServer.java
----------------------------------------------------------------------
diff --git a/jena-fuseki2/jena-fuseki-embedded/src/main/java/org/apache/jena/fuseki/embedded/JettyServer.java b/jena-fuseki2/jena-fuseki-embedded/src/main/java/org/apache/jena/fuseki/embedded/JettyServer.java
deleted file mode 100644
index 704060c..0000000
--- a/jena-fuseki2/jena-fuseki-embedded/src/main/java/org/apache/jena/fuseki/embedded/JettyServer.java
+++ /dev/null
@@ -1,369 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.jena.fuseki.embedded;
-
-import static java.lang.String.format;
-import static java.util.Objects.requireNonNull;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.Filter;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.jena.atlas.lib.Pair;
-import org.apache.jena.fuseki.Fuseki;
-import org.apache.jena.fuseki.server.DataAccessPointRegistry;
-import org.apache.jena.fuseki.servlets.ActionBase;
-import org.apache.jena.fuseki.servlets.ServiceDispatchRegistry;
-import org.apache.jena.riot.web.HttpNames;
-import org.apache.jena.web.HttpSC;
-import org.eclipse.jetty.http.HttpMethod;
-import org.eclipse.jetty.http.MimeTypes;
-import org.eclipse.jetty.security.SecurityHandler;
-import org.eclipse.jetty.server.HttpConnectionFactory;
-import org.eclipse.jetty.server.Request;
-import org.eclipse.jetty.server.Response;
-import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.server.ServerConnector;
-import org.eclipse.jetty.server.handler.ErrorHandler;
-import org.eclipse.jetty.servlet.DefaultServlet;
-import org.eclipse.jetty.servlet.FilterHolder;
-import org.eclipse.jetty.servlet.ServletContextHandler;
-import org.eclipse.jetty.servlet.ServletHolder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Jetty server for servlets, including being able to run Fuseki {@link ActionBase} derived servlets.
- * Static RDF types by file extension can be enabled.
- */
-public class JettyServer {
- // Use this for the super class of FusekiServer or as implementation inheritance.
- // Caution : there are small differences e.g. in building where order matters.
-
- private static Logger LOG = LoggerFactory.getLogger("HTTP");
-
- protected final Server server;
- protected int port;
-
- public static Builder create() {
- return new Builder();
- }
-
- protected JettyServer(int port, Server server) {
- this.server = server;
- this.port = port;
- }
-
- /**
- * Return the port begin used.
- * This will be the give port, which defaults to 3330, or
- * the one actually allocated if the port was 0 ("choose a free port").
- */
- public int getPort() {
- return port;
- }
-
- /** Get the underlying Jetty server which has also been set up. */
- public Server getJettyServer() {
- return server;
- }
-
- /** Get the {@link ServletContext}.
- * Adding new servlets is possible with care.
- */
- public ServletContext getServletContext() {
- return ((ServletContextHandler)server.getHandler()).getServletContext();
- }
-
- /** Start the server - the server continues to run after this call returns.
- * To synchronise with the server stopping, call {@link #join}.
- */
- public JettyServer start() {
- try { server.start(); }
- catch (Exception e) { throw new RuntimeException(e); }
- if ( port == 0 )
- port = ((ServerConnector)server.getConnectors()[0]).getLocalPort();
- logStart();
- return this;
- }
-
- protected void logStart() {
- LOG.info("Start (port="+port+")");
- }
-
- /** Stop the server. */
- public void stop() {
- logStop();
- try { server.stop(); }
- catch (Exception e) { throw new RuntimeException(e); }
- }
-
- protected void logStop() {
- LOG.info("Stop (port="+port+")");
- }
-
- /** Wait for the server to exit. This call is blocking. */
- public void join() {
- try { server.join(); }
- catch (Exception e) { throw new RuntimeException(e); }
- }
-
- /** One line error handler */
- public static class PlainErrorHandler extends ErrorHandler {
- // c.f. FusekiErrorHandler1
- public PlainErrorHandler() {}
-
- @Override
- public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException
- {
- String method = request.getMethod();
-
- if ( !method.equals(HttpMethod.GET.asString())
- && !method.equals(HttpMethod.POST.asString())
- && !method.equals(HttpMethod.HEAD.asString()) )
- return ;
-
- response.setContentType(MimeTypes.Type.TEXT_PLAIN_UTF_8.asString()) ;
- response.setHeader(HttpNames.hCacheControl, "must-revalidate,no-cache,no-store");
- response.setHeader(HttpNames.hPragma, "no-cache");
- int code = response.getStatus() ;
- String message=(response instanceof Response)?((Response)response).getReason(): HttpSC.getMessage(code) ;
- response.getOutputStream().print(format("Error %d: %s\n", code, message)) ;
- }
- }
-
- protected static class Builder {
- private int port = -1;
- private boolean loopback = false;
- protected boolean verbose = false;
- // Other servlets to add.
- private List<Pair<String, HttpServlet>> servlets = new ArrayList<>();
- private List<Pair<String, Filter>> filters = new ArrayList<>();
-
- private String contextPath = "/";
- private String servletContextName = "Jetty";
- private String staticContentDir = null;
- private SecurityHandler securityHandler = null;
- private ErrorHandler errorHandler = new PlainErrorHandler();
- private Map<String, Object> servletAttr = new HashMap<>();
-
- /** Set the port to run on. */
- public Builder port(int port) {
- if ( port < 0 )
- throw new IllegalArgumentException("Illegal port="+port+" : Port must be greater than or equal to zero.");
- this.port = port;
- return this;
- }
-
- /**
- * Context path. If it's "/" then Server URL will look like
- * "http://host:port/" else "http://host:port/path/"
- * (or no port if :80).
- */
- public Builder contextPath(String path) {
- requireNonNull(path, "path");
- this.contextPath = path;
- return this;
- }
-
- /**
- * ServletContextName.
- */
- public Builder servletContextName(String name) {
- requireNonNull(name, "name");
- this.servletContextName = name;
- return this;
- }
-
- /** Restrict the server to only responding to the localhost interface. */
- public Builder loopback(boolean loopback) {
- this.loopback = loopback;
- return this;
- }
-
- /** Set the location (filing system directory) to serve static file from. */
- public Builder staticFileBase(String directory) {
- requireNonNull(directory, "directory");
- this.staticContentDir = directory;
- return this;
- }
-
- /** Set a Jetty SecurityHandler.
- * <p>
- * By default, the server runs with no security.
- * This is more for using the basic server for testing.
- * The full Fuseki server provides security with Apache Shiro
- * and a defensive reverse proxy (e.g. Apache httpd) in front of the Jetty server
- * can also be used, which provides a wide varity of proven security options.
- */
- public Builder securityHandler(SecurityHandler securityHandler) {
- requireNonNull(securityHandler, "securityHandler");
- this.securityHandler = securityHandler;
- return this;
- }
-
- /** Set an {@link ErrorHandler}.
- * <p>
- * By default, the server runs with error handle that prints the code and message.
- */
- public Builder errorHandler(ErrorHandler errorHandler) {
- requireNonNull(errorHandler, "securityHandler");
- this.errorHandler = errorHandler;
- return this;
- }
-
- /** Set verbose logging */
- public Builder verbose(boolean verbose) {
- this.verbose = verbose;
- return this;
- }
-
- /**
- * Add the given servlet with the pathSpec. These are added so that they are
- * before the static content handler (which is the last servlet)
- * used for {@link #staticFileBase(String)}.
- */
- public Builder addServlet(String pathSpec, HttpServlet servlet) {
- requireNonNull(pathSpec, "pathSpec");
- requireNonNull(servlet, "servlet");
- servlets.add(Pair.create(pathSpec, servlet));
- return this;
- }
-
- /**
- * Add a servlet attribute. Pass a value of null to remove any existing binding.
- */
- public Builder addServletAttribute(String attrName, Object value) {
- requireNonNull(attrName, "attrName");
- if ( value != null )
- servletAttr.put(attrName, value);
- else
- servletAttr.remove(attrName);
- return this;
- }
-
- /**
- * Add the given filter with the pathSpec.
- * It is applied to all dispatch types.
- */
- public Builder addFilter(String pathSpec, Filter filter) {
- requireNonNull(pathSpec, "pathSpec");
- requireNonNull(filter, "filter");
- filters.add(Pair.create(pathSpec, filter));
- return this;
- }
-
- /**
- * Build a server according to the current description.
- */
- public JettyServer build() {
- ServletContextHandler handler = buildServletContext();
- // Use HandlerCollection for several ServletContextHandlers and thus several ServletContext.
- Server server = jettyServer(port, loopback);
- server.setHandler(handler);
- return new JettyServer(port, server);
- }
-
- /** Build a ServletContextHandler : one servlet context */
- private ServletContextHandler buildServletContext() {
- ServletContextHandler handler = buildServletContext(contextPath);
- ServletContext cxt = handler.getServletContext();
- adjustForFuseki(cxt);
- servletAttr.forEach((n,v)->cxt.setAttribute(n, v));
- servletsAndFilters(handler);
- return handler;
- }
-
- private void adjustForFuseki(ServletContext cxt) {
- // For Fuseki servlets added directly.
- // This enables servlets inheriting from {@link ActionBase} to work in the
- // plain Jetty server, e.g. to use Fuseki logging.
- try {
- Fuseki.setVerbose(cxt, verbose);
- ServiceDispatchRegistry.set(cxt, new ServiceDispatchRegistry(false));
- DataAccessPointRegistry.set(cxt, new DataAccessPointRegistry());
- } catch (NoClassDefFoundError err) {
- LOG.info("Fuseki classes not found");
- }
- }
-
- /** Build a ServletContextHandler. */
- private ServletContextHandler buildServletContext(String contextPath) {
- if ( contextPath == null || contextPath.isEmpty() )
- contextPath = "/";
- else if ( !contextPath.startsWith("/") )
- contextPath = "/" + contextPath;
- ServletContextHandler context = new ServletContextHandler();
- context.setDisplayName(servletContextName);
- context.setErrorHandler(errorHandler);
- context.setContextPath(contextPath);
- if ( securityHandler != null )
- context.setSecurityHandler(securityHandler);
-
- return context;
- }
-
- /** Add servlets and servlet filters */
- private void servletsAndFilters(ServletContextHandler context) {
- servlets.forEach(p-> addServlet(context, p.getLeft(), p.getRight()) );
- filters.forEach (p-> addFilter (context, p.getLeft(), p.getRight()) );
-
- if ( staticContentDir != null ) {
- DefaultServlet staticServlet = new DefaultServlet();
- ServletHolder staticContent = new ServletHolder(staticServlet);
- staticContent.setInitParameter("resourceBase", staticContentDir);
- context.addServlet(staticContent, "/");
- }
- }
-
- protected static void addServlet(ServletContextHandler context, String pathspec, HttpServlet httpServlet) {
- ServletHolder sh = new ServletHolder(httpServlet);
- context.addServlet(sh, pathspec);
- }
-
- protected void addFilter(ServletContextHandler context, String pathspec, Filter filter) {
- FilterHolder h = new FilterHolder(filter);
- context.addFilter(h, pathspec, null);
- }
-
- /** Jetty server */
- private static Server jettyServer(int port, boolean loopback) {
- Server server = new Server();
- HttpConnectionFactory f1 = new HttpConnectionFactory();
-
- //f1.getHttpConfiguration().setRequestHeaderSize(512 * 1024);
- //f1.getHttpConfiguration().setOutputBufferSize(1024 * 1024);
- f1.getHttpConfiguration().setSendServerVersion(false);
- ServerConnector connector = new ServerConnector(server, f1);
- connector.setPort(port);
- server.addConnector(connector);
- if ( loopback )
- connector.setHost("localhost");
- return server;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/jena/blob/7e6d03af/jena-fuseki2/jena-fuseki-embedded/src/test/java/org/apache/jena/fuseki/embedded/CustomService.java
----------------------------------------------------------------------
diff --git a/jena-fuseki2/jena-fuseki-embedded/src/test/java/org/apache/jena/fuseki/embedded/CustomService.java b/jena-fuseki2/jena-fuseki-embedded/src/test/java/org/apache/jena/fuseki/embedded/CustomService.java
deleted file mode 100644
index 5f4ec2d..0000000
--- a/jena-fuseki2/jena-fuseki-embedded/src/test/java/org/apache/jena/fuseki/embedded/CustomService.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.jena.fuseki.embedded;
-
-import java.io.IOException;
-
-import org.apache.jena.fuseki.servlets.ActionREST;
-import org.apache.jena.fuseki.servlets.HttpAction;
-import org.apache.jena.fuseki.servlets.ServletOps;
-import org.apache.jena.riot.WebContent;
-import org.apache.jena.web.HttpSC;
-
-public class CustomService extends ActionREST {
-
- // do* -- the operations to accept
-
- @Override
- protected void doGet(HttpAction action) {
- action.response.setStatus(HttpSC.OK_200);
- try {
- action.response.setContentType(WebContent.contentTypeTextPlain);
- action.response.getOutputStream().println(" ** Hello world (GET) **");
- }
- catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- @Override
- protected void doHead(HttpAction action) {
- action.response.setStatus(HttpSC.OK_200);
- action.response.setContentType(WebContent.contentTypeTextPlain);
- }
-
- @Override
- protected void doPost(HttpAction action) {
- action.response.setStatus(HttpSC.OK_200);
- try {
- action.response.setContentType(WebContent.contentTypeTextPlain);
- action.response.getOutputStream().println(" ** Hello world (POST) **");
- }
- catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- @Override
- protected void doPatch(HttpAction action) { notSupported(action); }
-
- @Override
- protected void doDelete(HttpAction action) { notSupported(action); }
-
- @Override
- protected void doPut(HttpAction action) { notSupported(action); }
-
- @Override
- protected void doOptions(HttpAction action) { notSupported(action); }
-
- @Override
- protected void validate(HttpAction action) { }
-
- private void notSupported(HttpAction action) {
- ServletOps.errorMethodNotAllowed(action.getMethod()+" "+action.getDatasetName());
- }
-}
http://git-wip-us.apache.org/repos/asf/jena/blob/7e6d03af/jena-fuseki2/jena-fuseki-embedded/src/test/java/org/apache/jena/fuseki/embedded/FusekiTestAuth.java
----------------------------------------------------------------------
diff --git a/jena-fuseki2/jena-fuseki-embedded/src/test/java/org/apache/jena/fuseki/embedded/FusekiTestAuth.java b/jena-fuseki2/jena-fuseki-embedded/src/test/java/org/apache/jena/fuseki/embedded/FusekiTestAuth.java
deleted file mode 100644
index 78bd8c7..0000000
--- a/jena-fuseki2/jena-fuseki-embedded/src/test/java/org/apache/jena/fuseki/embedded/FusekiTestAuth.java
+++ /dev/null
@@ -1,178 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.jena.fuseki.embedded;
-
-import java.util.Objects;
-
-import org.apache.jena.atlas.web.HttpException;
-import org.apache.jena.fuseki.FusekiLib;
-import org.apache.jena.fuseki.jetty.JettyLib;
-import org.apache.jena.sparql.core.DatasetGraph ;
-import org.apache.jena.sparql.core.DatasetGraphFactory;
-import org.apache.jena.web.HttpSC;
-import org.eclipse.jetty.security.*;
-import org.eclipse.jetty.security.authentication.BasicAuthenticator;
-import org.eclipse.jetty.util.security.Constraint;
-import org.junit.Assert;
-
-/**
- * Testing HTTP athentication.
- * <p>
- * {@code FusekiTestAuth} provides helper code for before/after (any of suite/class/test).
- * The pattern of usage is:
- * <pre>
- *
- * @BeforeClass
- * public static void beforeClassAuth() {
- * SecurityHandler sh = FusekiTestAuth.makeSimpleSecurityHandler("/*", "USER", "PASSWORD");
- * FusekiTestAuth.setupServer(true, sh);
- * }
- *
- * @AfterClass
- * public static void afterClassAuth() {
- * FusekiTestAuth.teardownServer();
- * // Clear up any pooled connections.
- * HttpOp.setDefaultHttpClient(HttpOp.createPoolingHttpClient());
- * }
- *
- * @Test
- * public void myAuthTest() {
- * BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
- * Credentials credentials = new UsernamePasswordCredentials("USER", "PASSWORD");
- * credsProvider.setCredentials(AuthScope.ANY, credentials);
- * HttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
- * try (TypedInputStream in = HttpOp.execHttpGet(ServerCtl.urlDataset(), "* /*", client, null)) {}
- * }
- *
- * @Test
- * public void myAuthTestRejected() {
- * BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
- * Credentials credentials = new UsernamePasswordCredentials("USER", "PASSWORD");
- * credsProvider.setCredentials(AuthScope.ANY, credentials);
- * HttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
- * try (TypedInputStream in = HttpOp.execHttpGet(ServerCtl.urlDataset(), "* /*", client, null)) {}
- * catch (HttpException ex) {
- * throw assertAuthHttpException(ex);
- * }
- * }
- * </pre>
- *
- * {@code @BeforeClass} can be {@code @Before} but server stop-start is expensive so a
- * large test suite may end up quite slow.
- */
-public class FusekiTestAuth {
- private static int currentPort = FusekiLib.choosePort() ;
-
- public static int port() {
- return currentPort ;
- }
-
- static boolean CLEAR_DSG_DIRECTLY = true ;
- static private DatasetGraph dsgTesting ;
-
- // Abstraction that runs a SPARQL server for tests.
- public static final String urlRoot() { return "http://localhost:"+port()+"/" ; }
- public static final String datasetPath() { return "/dataset" ; }
- public static final String urlDataset() { return "http://localhost:"+port()+datasetPath() ; }
- public static final DatasetGraph getDataset() { return dsgTesting ; }
-
- public static final String serviceUpdate() { return "http://localhost:"+port()+datasetPath()+"/update" ; }
- public static final String serviceQuery() { return "http://localhost:"+port()+datasetPath()+"/query" ; }
- public static final String serviceGSP() { return "http://localhost:"+port()+datasetPath()+"/data" ; }
-
- private static FusekiServer server ;
-
- /** Setup a testing server, using the given Jetty {@link SecurityHandler} for authentication.
- * The server will have an empty, in-emory transactional dataset.
- */
- public static void setupServer(boolean updateable, SecurityHandler sh) {
- setupServer(updateable, sh, DatasetGraphFactory.createTxnMem());
- }
-
- /** Setup a testing server, using the given Jetty {@link SecurityHandler} for authentication.
- */
- public static void setupServer(boolean updateable, SecurityHandler sh, DatasetGraph dsg) {
- dsgTesting = dsg;
- server = FusekiServer.create()
- .add(datasetPath(), dsgTesting)
- .port(port())
- .securityHandler(sh)
- .build()
- .start();
- }
-
- /** Shutdown the server.*/
- public static void teardownServer() {
- if ( server != null ) {
- server.stop() ;
- server = null ;
- dsgTesting = null;
- }
- }
-
- /** Create a Jetty {@link SecurityHandler} for basic authentication, one user/password/role. */
- public static SecurityHandler makeSimpleSecurityHandler(String pathSpec, String user, String password) {
- return makeSimpleSecurityHandler(pathSpec, null, user, password, "FusekiTestRole");
- }
-
- /** Create a Jetty {@link SecurityHandler} for basic authentication, one user/password/role. */
- public static SecurityHandler makeSimpleSecurityHandler(String pathSpec, String realm, String user, String password, String role) {
- Objects.requireNonNull(user);
- Objects.requireNonNull(password);
- Objects.requireNonNull(role);
-
- Constraint constraint = new Constraint() ;
- constraint.setName(Constraint.__BASIC_AUTH) ;
- String[] roles = new String[]{role};
- constraint.setRoles(roles) ;
- constraint.setAuthenticate(true) ;
-
- ConstraintMapping mapping = new ConstraintMapping() ;
- mapping.setConstraint(constraint) ;
- mapping.setPathSpec("/*") ;
-
- IdentityService identService = new DefaultIdentityService() ;
-
- ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler() ;
- securityHandler.addConstraintMapping(mapping) ;
- securityHandler.setIdentityService(identService) ;
-
- UserStore userStore = JettyLib.makeUserStore(user, password, role);
-
- HashLoginService loginService = new HashLoginService("Fuseki Authentication") ;
- loginService.setUserStore(userStore);
- loginService.setIdentityService(identService) ;
-
- securityHandler.setLoginService(loginService) ;
- securityHandler.setAuthenticator(new BasicAuthenticator()) ;
- if ( realm != null )
- securityHandler.setRealmName(realm);
-
- return securityHandler;
- }
-
- /** Assert that an {@code HttpException} ias an authorization failure.
- * This is normally 403. 401 indicates no retryu with credentials.
- */
- public static HttpException assertAuthHttpException(HttpException ex) {
- int rc = ex.getResponseCode();
- Assert.assertTrue(rc == HttpSC.FORBIDDEN_403 || rc == HttpSC.UNAUTHORIZED_401 );
- return ex;
- }
-}
http://git-wip-us.apache.org/repos/asf/jena/blob/7e6d03af/jena-fuseki2/jena-fuseki-embedded/src/test/java/org/apache/jena/fuseki/embedded/FusekiTestServer.java
----------------------------------------------------------------------
diff --git a/jena-fuseki2/jena-fuseki-embedded/src/test/java/org/apache/jena/fuseki/embedded/FusekiTestServer.java b/jena-fuseki2/jena-fuseki-embedded/src/test/java/org/apache/jena/fuseki/embedded/FusekiTestServer.java
deleted file mode 100644
index c8de9db..0000000
--- a/jena-fuseki2/jena-fuseki-embedded/src/test/java/org/apache/jena/fuseki/embedded/FusekiTestServer.java
+++ /dev/null
@@ -1,261 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.jena.fuseki.embedded;
-
-import static org.apache.jena.fuseki.embedded.FusekiTestServer.ServerScope.CLASS;
-import static org.apache.jena.fuseki.embedded.FusekiTestServer.ServerScope.SUITE;
-import static org.apache.jena.fuseki.embedded.FusekiTestServer.ServerScope.TEST;
-
-import java.util.concurrent.atomic.AtomicInteger ;
-
-import org.apache.http.client.HttpClient ;
-import org.apache.http.impl.client.CloseableHttpClient ;
-import org.apache.jena.atlas.io.IO ;
-import org.apache.jena.fuseki.FusekiLib;
-import org.apache.jena.riot.web.HttpOp ;
-import org.apache.jena.sparql.core.DatasetGraph ;
-import org.apache.jena.sparql.core.DatasetGraphFactory;
-import org.apache.jena.sparql.modify.request.Target ;
-import org.apache.jena.sparql.modify.request.UpdateDrop ;
-import org.apache.jena.system.Txn ;
-import org.apache.jena.update.Update ;
-import org.apache.jena.update.UpdateExecutionFactory ;
-import org.apache.jena.update.UpdateProcessor ;
-
-/**
- * Manage a single server for use with tests. It supports three modes:
- * <ul>
- * <li>One server for a whole test suite
- * <li>One server per test class
- * <li>One server per individual test
- * </ul>
- * One server per individual test can be troublesome due to connections not closing down
- * fast enough (left in TCP state {@code TIME_WAIT} which is 2 minutes) and also can be
- * slow. One server per test class is a good compromise.
- * <p>
- * The data in the server is always reseet between tests.
- * <p>
- * Using a connection pooling HttpClient (see {@link HttpOp#createPoolingHttpClient()}) is
- * important, both for test performance and for reducing the TCP connection load on the
- * operating system.
- * <p>
- * Usage:
- * </p>
- * <p>
- * In the test suite, put:
- *
- * <pre>
- * {@literal @BeforeClass} static public void beforeSuiteClass() { FusekiTestServer.ctlBeforeTestSuite(); }
- * {@literal @AfterClass} static public void afterSuiteClass() { FusekiTestServer.ctlAfterTestSuite(); }
- * </pre>
- * <p>
- * In the test class, put:
- *
- * <pre>
- * {@literal @BeforeClass} public static void ctlBeforeClass() { FusekiTestServer.ctlBeforeClass(); }
- * {@literal @AfterClass} public static void ctlAfterClass() { FusekiTestServer.ctlAfterClass(); }
- * {@literal @Before} public void ctlBeforeTest() { FusekiTestServer.ctlBeforeTest(); }
- * {@literal @After} public void ctlAfterTest() { FusekiTestServer.ctlAfterTest(); }
- * </pre>
- *
- * Much of this machinery is unnessecary for just running a sever in the background:
- *
- * <pre>
- * private static FusekiServer server ;
- * private static DatasetGraph serverdsg = DatasetGraphFactory.createTxnMem() ;
- *
- * @BeforeClass
- * public static void beforeClass() {
- * server = FusekiServer.create()
- * .setPort(....)
- * .add("/ds", serverdsg)
- * .build()
- * .start();
- * }
- *
- * @Before
- * public void beforeTest() {
- * // Clear up data in server servers
- * Txn.executeWrite(serverdsg, ()->serverdsg.clear()) ;
- * }
- *
- * @AfterClass
- * public static void afterClass() {
- * server.stop();
- * }
- * </pre>
- */
-public class FusekiTestServer {
- /* Cut&Paste versions:
-
- Test suite (TS_*)
- @BeforeClass static public void beforeSuiteClass() { FusekiTestServer.ctlBeforeTestSuite(); }
- @AfterClass static public void afterSuiteClass() { FusekiTestServer.ctlAfterTestSuite(); }
-
- Test class (Test*)
- @BeforeClass public static void ctlBeforeClass() { FusekiTestServer.ctlBeforeClass(); }
- @AfterClass public static void ctlAfterClass() { FusekiTestServer.ctlAfterClass(); }
- @Before public void ctlBeforeTest() { FusekiTestServer.ctlBeforeTest(); }
- @After public void ctlAfterTest() { FusekiTestServer.ctlAfterTest(); }
-
- */
-
- // Note: it is important to cleanly close a PoolingHttpClient across server restarts
- // otherwise the pooled connections remain for the old server.
-
- /*package : for import static */ enum ServerScope { SUITE, CLASS, TEST }
- private static ServerScope serverScope = ServerScope.CLASS ;
- private static int currentPort = FusekiLib.choosePort() ;
-
- public static int port() {
- return currentPort ;
- }
-
- // Whether to use a transaction on the dataset or to use SPARQL Update.
- static boolean CLEAR_DSG_DIRECTLY = true ;
- static private DatasetGraph dsgTesting ;
-
- // Abstraction that runs a SPARQL server for tests.
- public static final String urlRoot() { return "http://localhost:"+port()+"/" ; }
- public static final String datasetPath() { return "/dataset" ; }
- public static final String urlDataset() { return "http://localhost:"+port()+datasetPath() ; }
-
- public static final String serviceUpdate() { return "http://localhost:"+port()+datasetPath()+"/update" ; }
- public static final String serviceQuery() { return "http://localhost:"+port()+datasetPath()+"/query" ; }
- public static final String serviceGSP() { return "http://localhost:"+port()+datasetPath()+"/data" ; }
-
- public static void ctlBeforeTestSuite() {
- if ( serverScope == SUITE ) {
- setPoolingHttpClient() ;
- allocServer();
- }
- }
-
- public static void ctlAfterTestSuite() {
- if ( serverScope == SUITE ) {
- freeServer();
- resetDefaultHttpClient() ;
- }
- }
-
- /**
- * Setup for the tests by allocating a Fuseki instance to work with
- */
- public static void ctlBeforeClass() {
- if ( serverScope == CLASS ) {
- setPoolingHttpClient() ;
- allocServer();
- }
- }
-
- /**
- * Clean up after tests by de-allocating the Fuseki instance
- */
- public static void ctlAfterClass() {
- if ( serverScope == CLASS ) {
- freeServer();
- resetDefaultHttpClient() ;
- }
- }
-
- /**
- * Placeholder.
- */
- public static void ctlBeforeTest() {
- if ( serverScope == TEST ) {
- setPoolingHttpClient() ;
- allocServer();
- }
- }
-
- /**
- * Clean up after each test by resetting the Fuseki dataset
- */
- public static void ctlAfterTest() {
- if ( serverScope == TEST ) {
- freeServer();
- resetDefaultHttpClient() ;
- } else
- resetServer();
- }
-
- /** Set a PoolingHttpClient */
- public static void setPoolingHttpClient() {
- setHttpClient(HttpOp.createPoolingHttpClient()) ;
- }
-
- /** Restore the original setup */
- private static void resetDefaultHttpClient() {
- setHttpClient(HttpOp.createDefaultHttpClient());
- }
-
- /** Set the HttpClient - close the old one if appropriate */
- public static void setHttpClient(HttpClient newHttpClient) {
- HttpClient hc = HttpOp.getDefaultHttpClient() ;
- if ( hc instanceof CloseableHttpClient )
- IO.close((CloseableHttpClient)hc) ;
- HttpOp.setDefaultHttpClient(newHttpClient) ;
- }
-
- // reference count of start/stop server
- private static AtomicInteger countServer = new AtomicInteger() ;
- private static FusekiServer server = null ;
-
- /*package*/ static void allocServer() {
- if ( countServer.getAndIncrement() == 0 )
- setupServer(true) ;
- }
-
- /*package*/ static void freeServer() {
- if ( countServer.decrementAndGet() == 0 )
- teardownServer() ;
- }
-
- /*package*/ static void setupServer(boolean updateable) {
- dsgTesting = DatasetGraphFactory.createTxnMem();
- server = FusekiServer.create()
- .add(datasetPath(), dsgTesting)
- .port(port())
- .build()
- .start();
- }
-
- /*package*/ static void teardownServer() {
- if ( server != null ) {
- server.stop() ;
- server = null ;
- }
- }
-
- /*package*/ static void resetServer() {
- if (countServer.get() == 0)
- throw new RuntimeException("No server started!");
- if ( CLEAR_DSG_DIRECTLY ) {
- Txn.executeWrite(dsgTesting, ()->dsgTesting.clear()) ;
- } else {
- Update clearRequest = new UpdateDrop(Target.ALL) ;
- UpdateProcessor proc = UpdateExecutionFactory.createRemote(clearRequest, serviceUpdate()) ;
- try {proc.execute() ; }
- catch (Throwable e) {e.printStackTrace(); throw e;}
- }
- }
-
- // ---- Helper code.
-
-}
http://git-wip-us.apache.org/repos/asf/jena/blob/7e6d03af/jena-fuseki2/jena-fuseki-embedded/src/test/java/org/apache/jena/fuseki/embedded/TS_EmbeddedFuseki.java
----------------------------------------------------------------------
diff --git a/jena-fuseki2/jena-fuseki-embedded/src/test/java/org/apache/jena/fuseki/embedded/TS_EmbeddedFuseki.java b/jena-fuseki2/jena-fuseki-embedded/src/test/java/org/apache/jena/fuseki/embedded/TS_EmbeddedFuseki.java
deleted file mode 100644
index d7efb9f..0000000
--- a/jena-fuseki2/jena-fuseki-embedded/src/test/java/org/apache/jena/fuseki/embedded/TS_EmbeddedFuseki.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.jena.fuseki.embedded;
-
-import org.apache.jena.atlas.logging.LogCtl ;
-import org.apache.jena.fuseki.Fuseki ;
-import org.junit.BeforeClass ;
-import org.junit.runner.RunWith ;
-import org.junit.runners.Suite ;
-import org.junit.runners.Suite.SuiteClasses ;
-
-@RunWith(Suite.class)
-@SuiteClasses({
- TestEmbeddedFuseki.class
- , TestMultipleEmbedded.class
- , TestFusekiTestServer.class
- , TestFusekiTestAuth.class
- , TestFusekiCustomOperation.class
-})
-public class TS_EmbeddedFuseki {
- @BeforeClass public static void setupForFusekiServer() {
- LogCtl.setLevel(Fuseki.serverLogName, "WARN");
- LogCtl.setLevel(Fuseki.actionLogName, "WARN");
- LogCtl.setLevel(Fuseki.requestLogName, "WARN");
- LogCtl.setLevel(Fuseki.adminLogName, "WARN");
- LogCtl.setLevel("org.eclipse.jetty", "WARN");
-
- // Shouldn't see these in the embedded server.
-// LogCtl.setLevel("org.apache.shiro", "WARN") ;
-// LogCtl.setLevel(Fuseki.configLogName, "WARN");
-
-// LogCtl.setLevel(Fuseki.builderLogName, "WARN");
-// LogCtl.setLevel(Fuseki.servletRequestLogName,"WARN");
- }
-}
http://git-wip-us.apache.org/repos/asf/jena/blob/7e6d03af/jena-fuseki2/jena-fuseki-embedded/src/test/java/org/apache/jena/fuseki/embedded/TestEmbeddedFuseki.java
----------------------------------------------------------------------
diff --git a/jena-fuseki2/jena-fuseki-embedded/src/test/java/org/apache/jena/fuseki/embedded/TestEmbeddedFuseki.java b/jena-fuseki2/jena-fuseki-embedded/src/test/java/org/apache/jena/fuseki/embedded/TestEmbeddedFuseki.java
deleted file mode 100644
index 0d82a6e..0000000
--- a/jena-fuseki2/jena-fuseki-embedded/src/test/java/org/apache/jena/fuseki/embedded/TestEmbeddedFuseki.java
+++ /dev/null
@@ -1,321 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.jena.fuseki.embedded;
-
-import static org.junit.Assert.assertEquals ;
-import static org.junit.Assert.assertFalse ;
-import static org.junit.Assert.assertNotNull ;
-import static org.junit.Assert.assertNull ;
-import static org.junit.Assert.assertTrue ;
-
-import java.io.OutputStream ;
-import java.util.function.Consumer ;
-
-import org.apache.http.HttpEntity ;
-import org.apache.http.entity.ContentProducer ;
-import org.apache.http.entity.EntityTemplate ;
-import org.apache.jena.atlas.web.ContentType ;
-import org.apache.jena.atlas.web.HttpException ;
-import org.apache.jena.atlas.web.TypedInputStream ;
-import org.apache.jena.fuseki.FusekiLib;
-import org.apache.jena.fuseki.server.DataAccessPointRegistry ;
-import org.apache.jena.fuseki.server.DataService ;
-import org.apache.jena.fuseki.server.Operation ;
-import org.apache.jena.graph.Graph ;
-import org.apache.jena.query.QueryExecution;
-import org.apache.jena.query.QueryExecutionFactory;
-import org.apache.jena.query.ResultSet;
-import org.apache.jena.query.ResultSetFormatter;
-import org.apache.jena.riot.RDFDataMgr ;
-import org.apache.jena.riot.RDFFormat ;
-import org.apache.jena.riot.RDFLanguages ;
-import org.apache.jena.riot.web.HttpOp ;
-import org.apache.jena.sparql.core.DatasetGraph ;
-import org.apache.jena.sparql.core.DatasetGraphFactory ;
-import org.apache.jena.sparql.core.Quad ;
-import org.apache.jena.sparql.graph.GraphFactory ;
-import org.apache.jena.sparql.sse.SSE ;
-import org.apache.jena.system.Txn ;
-import org.apache.jena.update.UpdateExecutionFactory ;
-import org.apache.jena.update.UpdateFactory ;
-import org.apache.jena.update.UpdateRequest ;
-import org.apache.jena.web.HttpSC ;
-import org.junit.Test ;
-
-public class TestEmbeddedFuseki {
-
- private static final String DIR = "testing/FusekiEmbedded/" ;
-
- // Test - build on default port.
- @Test public void embedded_01() {
- DatasetGraph dsg = dataset() ;
- int port = 3330 ; // Default port.
- FusekiServer server = FusekiServer.create().add("/ds", dsg).build() ;
- assertTrue(server.getDataAccessPointRegistry().isRegistered("/ds")) ;
- server.start() ;
- query("http://localhost:"+port+"/ds/query", "SELECT * { ?s ?p ?o}", qExec-> {
- ResultSet rs = qExec.execSelect() ;
- assertFalse(rs.hasNext()) ;
- }) ;
- server.stop() ;
- }
-
- // Different dataset name.
- @Test public void embedded_02() {
- DatasetGraph dsg = dataset() ;
- int port = 0 ;//FusekiEnv.choosePort() ;
- FusekiServer server = FusekiServer.make(port, "/ds2", dsg) ;
- DataAccessPointRegistry registry = server.getDataAccessPointRegistry() ;
- // But no /ds
- assertEquals(1, registry.size()) ;
- assertTrue(registry.isRegistered("/ds2")) ;
- assertFalse(registry.isRegistered("/ds")) ;
- try {
- server.start() ;
- } finally { server.stop() ; }
- }
-
- // Different dataset name.
- @Test public void embedded_03() {
- DatasetGraph dsg = dataset() ;
- int port = FusekiLib.choosePort() ;
- FusekiServer server = FusekiServer.create()
- .port(port)
- .add("/ds1", dsg)
- .build() ;
- server.start() ;
- try {
- // Add while live.
- Txn.executeWrite(dsg, ()->{
- Quad q = SSE.parseQuad("(_ :s :p _:b)") ;
- dsg.add(q);
- }) ;
- query("http://localhost:"+port+"/ds1/query", "SELECT * { ?s ?p ?o}", qExec->{
- ResultSet rs = qExec.execSelect() ;
- int x = ResultSetFormatter.consume(rs) ;
- assertEquals(1, x) ;
- }) ;
- } finally { server.stop() ; }
- }
-
-
- @Test public void embedded_04() {
- DatasetGraph dsg = dataset() ;
- Txn.executeWrite(dsg, ()->{
- Quad q = SSE.parseQuad("(_ :s :p _:b)") ;
- dsg.add(q);
- }) ;
-
- // A service with just being able to do quads operations
- // That is, GET, POST, PUT on "/data" in N-quads and TriG.
- DataService dataService = new DataService(dsg) ;
- dataService.addEndpoint(Operation.Quads_RW, "");
- dataService.addEndpoint(Operation.Query, "");
- dataService.addEndpoint(Operation.Update, "");
- int port = FusekiLib.choosePort() ;
-
- FusekiServer server = FusekiServer.create()
- .port(port)
- .add("/data", dataService)
- .build() ;
- server.start() ;
- try {
- // Put data in.
- String data = "(graph (:s :p 1) (:s :p 2) (:s :p 3))" ;
- Graph g = SSE.parseGraph(data) ;
- HttpEntity e = graphToHttpEntity(g) ;
- HttpOp.execHttpPut("http://localhost:"+port+"/data", e) ;
-
- // Get data out.
- try ( TypedInputStream in = HttpOp.execHttpGet("http://localhost:"+port+"/data") ) {
- Graph g2 = GraphFactory.createDefaultGraph() ;
- RDFDataMgr.read(g2, in, RDFLanguages.contentTypeToLang(in.getContentType())) ;
- assertTrue(g.isIsomorphicWith(g2)) ;
- }
- // Query.
- query("http://localhost:"+port+"/data", "SELECT * { ?s ?p ?o}", qExec->{
- ResultSet rs = qExec.execSelect() ;
- int x = ResultSetFormatter.consume(rs) ;
- assertEquals(3, x) ;
- }) ;
- // Update
- UpdateRequest req = UpdateFactory.create("CLEAR DEFAULT") ;
- UpdateExecutionFactory.createRemote(req, "http://localhost:"+port+"/data").execute();
- // Query again.
- query("http://localhost:"+port+"/data", "SELECT * { ?s ?p ?o}", qExec-> {
- ResultSet rs = qExec.execSelect() ;
- int x = ResultSetFormatter.consume(rs) ;
- assertEquals(0, x) ;
- }) ;
- } finally { server.stop() ; }
- }
-
- @Test public void embedded_05() {
- DatasetGraph dsg = dataset() ;
- int port = FusekiLib.choosePort() ;
- FusekiServer server = FusekiServer.create()
- .port(port)
- .add("/ds0", dsg)
- .build() ;
- server.start() ;
- try {
- // No stats
- String x = HttpOp.execHttpGetString("http://localhost:"+port+"/$/stats") ;
- assertNull(x) ;
- } finally { server.stop() ; }
- }
-
- @Test public void embedded_06() {
- DatasetGraph dsg = dataset() ;
- int port = FusekiLib.choosePort() ;
- FusekiServer server = FusekiServer.create()
- .port(port)
- .add("/ds0", dsg)
- .enableStats(true)
- .build() ;
- server.start() ;
- // No stats
- String x = HttpOp.execHttpGetString("http://localhost:"+port+"/$/stats") ;
- assertNotNull(x) ;
- server.stop() ;
- }
-
- // Context path.
- @Test public void embedded_07() {
- DatasetGraph dsg = dataset() ;
- int port = FusekiLib.choosePort() ;
-
- FusekiServer server = FusekiServer.create()
- .port(port)
- .contextPath("/ABC")
- .add("/ds", dsg)
- .build() ;
- server.start() ;
- try {
- String x1 = HttpOp.execHttpGetString("http://localhost:"+port+"/ds") ;
- assertNull(x1) ;
- String x2 = HttpOp.execHttpGetString("http://localhost:"+port+"/ABC/ds") ;
- assertNotNull(x2) ;
- } finally { server.stop() ; }
- }
-
- @Test public void embedded_08() {
- DatasetGraph dsg = dataset() ;
- int port = FusekiLib.choosePort() ;
-
- FusekiServer server = FusekiServer.create()
- .port(port)
- .parseConfigFile(DIR+"config.ttl")
- .build() ;
- server.start() ;
- try {
- query("http://localhost:"+port+"/FuTest", "SELECT * {}", x->{}) ;
- } finally { server.stop() ; }
- }
-
- @Test public void embedded_09() {
- DatasetGraph dsg = dataset() ;
- int port = FusekiLib.choosePort() ;
-
- FusekiServer server = FusekiServer.create()
- .port(port)
- .contextPath("/ABC")
- .parseConfigFile(DIR+"config.ttl")
- .build() ;
- server.start() ;
- try {
- try {
- query("http://localhost:"+port+"/FuTest", "ASK{}", x->{}) ;
- } catch (HttpException ex) {
- assertEquals(HttpSC.METHOD_NOT_ALLOWED_405, ex.getResponseCode()) ;
- }
-
- query("http://localhost:"+port+"/ABC/FuTest","ASK{}",x->{}) ;
- } finally { server.stop() ; }
- }
-
- @Test public void embedded_20() {
- DatasetGraph dsg = dataset() ;
- int port = FusekiLib.choosePort() ;
-
- DataService dSrv = new DataService(dsg) ;
- dSrv.addEndpoint(Operation.Query, "q") ;
- dSrv.addEndpoint(Operation.GSP_R, "gsp") ;
- FusekiServer server = FusekiServer.create()
- .add("/dsrv1", dSrv)
- .port(port)
- .build() ;
- server.start() ;
- try {
- query("http://localhost:"+port+"/dsrv1/q","ASK{}",x->{}) ;
- String x1 = HttpOp.execHttpGetString("http://localhost:"+port+"/dsrv1/gsp") ;
- assertNotNull(x1) ;
- } finally { server.stop() ; }
- }
-
- @Test public void embedded_21() {
- DatasetGraph dsg = dataset() ;
- int port = FusekiLib.choosePort() ;
-
- DataService dSrv = new DataService(dsg) ;
- dSrv.addEndpoint(Operation.Query, "q") ;
- dSrv.addEndpoint(Operation.GSP_R, "gsp") ;
- FusekiServer server = FusekiServer.create()
- .add("/dsrv1", dSrv)
- .staticFileBase(DIR)
- .port(port)
- .build() ;
- server.start() ;
-
- try {
- query("http://localhost:"+port+"/dsrv1/q","ASK{}",x->{}) ;
- String x1 = HttpOp.execHttpGetString("http://localhost:"+port+"/dsrv1/gsp") ;
- assertNotNull(x1) ;
- // Static
- String x2 = HttpOp.execHttpGetString("http://localhost:"+port+"/test.txt");
- assertNotNull(x2) ;
- } finally { server.stop() ; }
- }
-
-
- /** Create an HttpEntity for the graph */
- protected static HttpEntity graphToHttpEntity(final Graph graph) {
- final RDFFormat syntax = RDFFormat.TURTLE_BLOCKS ;
- ContentProducer producer = new ContentProducer() {
- @Override
- public void writeTo(OutputStream out) {
- RDFDataMgr.write(out, graph, syntax) ;
- }
- } ;
- EntityTemplate entity = new EntityTemplate(producer) ;
- ContentType ct = syntax.getLang().getContentType() ;
- entity.setContentType(ct.getContentType()) ;
- return entity ;
- }
-
- /*package*/ static DatasetGraph dataset() {
- return DatasetGraphFactory.createTxnMem() ;
- }
-
- /*package*/ static void query(String URL, String query, Consumer<QueryExecution> body) {
- try (QueryExecution qExec = QueryExecutionFactory.sparqlService(URL, query) ) {
- body.accept(qExec);
- }
- }
-}