diff --git a/parameters-application/parameters-app-support/pom.xml b/parameters-application/parameters-app-support/pom.xml index 64a2716..3718e81 100644 --- a/parameters-application/parameters-app-support/pom.xml +++ b/parameters-application/parameters-app-support/pom.xml @@ -70,12 +70,12 @@ org.slf4j slf4j-api - - - - - - + + com.sun.jersey + jersey-client + 1.19.1 + runtime + diff --git a/parameters-application/parameters-app-support/src/main/java/be/kwakeroni/parameters/app/support/MainWaiter.java b/parameters-application/parameters-app-support/src/main/java/be/kwakeroni/parameters/app/support/MainWaiter.java new file mode 100644 index 0000000..790a9c7 --- /dev/null +++ b/parameters-application/parameters-app-support/src/main/java/be/kwakeroni/parameters/app/support/MainWaiter.java @@ -0,0 +1,21 @@ +package be.kwakeroni.parameters.app.support; + +import java.io.IOException; +import java.io.UncheckedIOException; + +public class MainWaiter { + + public static void waitForExit() { + try { + System.out.println("Press 'q' to exit"); + int input = 0; + while (input != 'q') { + // Thread.onSpinWait(); + input = System.in.read(); + } + } catch (IOException exc) { + throw new UncheckedIOException(exc); + } + } + +} diff --git a/parameters-application/parameters-app-support/src/main/java/be/kwakeroni/parameters/app/support/SimpleRestServer.java b/parameters-application/parameters-app-support/src/main/java/be/kwakeroni/parameters/app/support/SimpleRestServer.java index 55984ef..1d5fc12 100644 --- a/parameters-application/parameters-app-support/src/main/java/be/kwakeroni/parameters/app/support/SimpleRestServer.java +++ b/parameters-application/parameters-app-support/src/main/java/be/kwakeroni/parameters/app/support/SimpleRestServer.java @@ -54,6 +54,7 @@ protected synchronized void start() throws IOException { protected synchronized void stop() { if (this.httpServer != null) { + LOG.info("Shutting down server at {}", this.httpServer.getAddress()); this.httpServer.stop(0); this.httpServer = null; } diff --git a/parameters-application/parameters-app-support/src/main/java/be/kwakeroni/parameters/app/support/StaticContentFactory.java b/parameters-application/parameters-app-support/src/main/java/be/kwakeroni/parameters/app/support/StaticContentFactory.java index 58a5ac1..5acd88a 100644 --- a/parameters-application/parameters-app-support/src/main/java/be/kwakeroni/parameters/app/support/StaticContentFactory.java +++ b/parameters-application/parameters-app-support/src/main/java/be/kwakeroni/parameters/app/support/StaticContentFactory.java @@ -23,7 +23,7 @@ private StaticContentFactory() { } public static StaticContent fromZip(Supplier zipFile, String indexFile, Path workDir) { - LOG.info("Buffering web application into {}", workDir); + LOG.info("Buffering web application into {}", workDir.toAbsolutePath()); try { Files.createDirectories(workDir); diff --git a/parameters-application/parameters-standalone-app/src/main/java/be/kwakeroni/parameters/app/Application.java b/parameters-application/parameters-standalone-app/src/main/java/be/kwakeroni/parameters/app/Application.java index 5ef0ac1..436fd60 100644 --- a/parameters-application/parameters-standalone-app/src/main/java/be/kwakeroni/parameters/app/Application.java +++ b/parameters-application/parameters-standalone-app/src/main/java/be/kwakeroni/parameters/app/Application.java @@ -1,5 +1,6 @@ package be.kwakeroni.parameters.app; +import be.kwakeroni.parameters.app.support.MainWaiter; import be.kwakeroni.parameters.backend.api.Configuration; import be.kwakeroni.parameters.core.support.backend.ConfigurationSupport; import be.kwakeroni.parameters.core.support.util.function.ThrowingPredicate; @@ -13,29 +14,49 @@ import java.io.File; import java.io.IOException; -import java.io.UncheckedIOException; import java.net.URI; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Optional; +import java.util.Properties; import java.util.function.UnaryOperator; import static be.kwakeroni.parameters.core.support.util.function.ThrowingFunction.unchecked; public class Application { + private final Server server; + public static void main(String[] args) throws Exception { initLogging(); try { - createServer(args) - .ifPresent(Application::start); + Optional app = create(args); + if (app.isPresent()) { + try (AutoCloseable closeable = app.get().start()) { + MainWaiter.waitForExit(); + } + } } catch (ParseException exc) { System.out.println(exc.getMessage()); Opt.HELP.handle(""); } } + public static Optional create(String... args) throws CLIException, ParseException { + return createServer(args) + .map(Application::new); + } + + public static Optional create(Properties configurationProperties) { + return createServer(configurationProperties) + .map(Application::new); + } + + private Application(Server server) { + this.server = server; + } + private static void initLogging() { System.out.println("log4j.configuration=" + System.getProperty("log4j.configuration")); if (System.getProperty("log4j.configuration") == null) { @@ -45,20 +66,12 @@ private static void initLogging() { } } - private static void start(Server resource) { - try (Server server = resource) { - server.start(); - - while (true) { - // Thread.onSpinWait(); - } - - } catch (IOException exc) { - throw new UncheckedIOException(exc); - } + public AutoCloseable start() throws IOException { + this.server.start(); + return this.server; } - static Optional createServer(String[] args) throws Exception { + static Optional createServer(String[] args) throws CLIException, ParseException { CommandLineParser clParser = new DefaultParser(); CommandLine commandLine = clParser.parse(CLI_OPTIONS, args); @@ -71,6 +84,12 @@ static Optional createServer(String[] args) throws Exception { return Optional.of(new Server()); } + static Optional createServer(Properties configurationProperties) { + Configuration configuration = ConfigurationSupport.of(configurationProperties); + ServerConfigurationProvider.setConfiguration(configuration); + return Optional.of(new Server()); + } + private static final Options CLI_OPTIONS; @@ -128,7 +147,7 @@ private String getOptKey() { return (this.opt != null) ? this.opt : this.option.getLongOpt(); } - boolean handle(CommandLine commandLine) throws Exception { + boolean handle(CommandLine commandLine) throws CLIException { if (commandLine.hasOption(getOptKey())) { String optValue = commandLine.getOptionValue(getOptKey()); return handle(optValue); @@ -136,8 +155,12 @@ boolean handle(CommandLine commandLine) throws Exception { return true; } - boolean handle(String value) throws Exception { - return this.handler.test(value); + boolean handle(String value) throws CLIException { + try { + return this.handler.test(value); + } catch (Exception e) { + throw new CLIException(e); + } } } @@ -155,4 +178,18 @@ private static String getJarFileName() { .orElse("parameters-standalone-app.jar"); } + + public static class CLIException extends Exception { + public CLIException(String message) { + super(message); + } + + public CLIException(String message, Throwable cause) { + super(message, cause); + } + + public CLIException(Throwable cause) { + super(cause); + } + } } diff --git a/parameters-backend/parameters-backend-inmemory/src/main/java/be/kwakeroni/evelyn/storage/impl/FileStorageProvider.java b/parameters-backend/parameters-backend-inmemory/src/main/java/be/kwakeroni/evelyn/storage/impl/FileStorageProvider.java index 0be5f4d..fb34e3b 100644 --- a/parameters-backend/parameters-backend-inmemory/src/main/java/be/kwakeroni/evelyn/storage/impl/FileStorageProvider.java +++ b/parameters-backend/parameters-backend-inmemory/src/main/java/be/kwakeroni/evelyn/storage/impl/FileStorageProvider.java @@ -12,6 +12,9 @@ public class FileStorageProvider implements StorageProvider { private final Path storageDirectory; public FileStorageProvider(Path storageDirectory) { + if (! Files.exists(storageDirectory)){ + throw new IllegalStateException("Storage directory does not exist: " + storageDirectory.toAbsolutePath()); + } this.storageDirectory = storageDirectory; } diff --git a/parameters-backend/parameters-backend-inmemory/src/main/java/be/kwakeroni/parameters/backend/inmemory/factory/InMemoryBackendServiceFactory.java b/parameters-backend/parameters-backend-inmemory/src/main/java/be/kwakeroni/parameters/backend/inmemory/factory/InMemoryBackendServiceFactory.java index 04db343..01473e8 100644 --- a/parameters-backend/parameters-backend-inmemory/src/main/java/be/kwakeroni/parameters/backend/inmemory/factory/InMemoryBackendServiceFactory.java +++ b/parameters-backend/parameters-backend-inmemory/src/main/java/be/kwakeroni/parameters/backend/inmemory/factory/InMemoryBackendServiceFactory.java @@ -108,7 +108,7 @@ private static GroupDataStore getDefaultDataStoreSupplier() { private static GroupDataStore persistentStore(Path location) { FileStorageProvider provider = new FileStorageProvider(location); PersistedGroupDataStore store = new PersistedGroupDataStore(provider); - LOG.info("Using persistent data store at {}", location); + LOG.info("Using persistent data store at {}", location.toAbsolutePath()); return store; } diff --git a/parameters-basic/parameters-basic-wireformat-json/src/main/java/be/kwakeroni/parameters/basic/wireformat/json/BasicJsonWireFormat.java b/parameters-basic/parameters-basic-wireformat-json/src/main/java/be/kwakeroni/parameters/basic/wireformat/json/BasicJsonWireFormat.java index 493a6cb..efb5034 100644 --- a/parameters-basic/parameters-basic-wireformat-json/src/main/java/be/kwakeroni/parameters/basic/wireformat/json/BasicJsonWireFormat.java +++ b/parameters-basic/parameters-basic-wireformat-json/src/main/java/be/kwakeroni/parameters/basic/wireformat/json/BasicJsonWireFormat.java @@ -55,20 +55,20 @@ private Q tryInternalize0(BackendGroup group, JSONObject query, BackendWi } @Override - public Object externalizeValueQuery(ValueQuery query, ClientWireFormatterContext context) { + public JSONObject externalizeValueQuery(ValueQuery query, ClientWireFormatterContext context) { return new JSONObject() .put(TYPE, TYPE_VALUE) .put(PARAMETER, query.getParameter().getName()); } @Override - public Object externalizeEntryQuery(EntryQuery query, ClientWireFormatterContext context) { + public JSONObject externalizeEntryQuery(EntryQuery query, ClientWireFormatterContext context) { return new JSONObject() .put(TYPE, TYPE_ENTRY); } @Override - public Object externalizeMappedQuery(MappedQuery query, ClientWireFormatterContext context) { + public JSONObject externalizeMappedQuery(MappedQuery query, ClientWireFormatterContext context) { return new JSONObject() .put(TYPE, TYPE_MAPPED) .put(KEY, query.getKeyString()) @@ -76,7 +76,7 @@ public Object externalizeMappedQuery(MappedQuery query, ClientWireForma } @Override - public Object externalizeRangedQuery(RangedQuery query, ClientWireFormatterContext context) { + public JSONObject externalizeRangedQuery(RangedQuery query, ClientWireFormatterContext context) { return new JSONObject() .put(TYPE, TYPE_RANGED) .put(VALUE, query.getValueString()) @@ -84,7 +84,7 @@ public Object externalizeRangedQuery(RangedQuery query, ClientWireForma } @Override - public Object clientValueToWire(T value, ValueQuery query, ClientWireFormatterContext context) { + public String clientValueToWire(T value, ValueQuery query, ClientWireFormatterContext context) { return (value == null) ? null : query.getParameter().toString(value); } @@ -94,13 +94,13 @@ public T wireToClientValue(Object result, ValueQuery query, ClientWireFor } @Override - public Object clientEntryToWire(Entry entry, EntryQuery query, ClientWireFormatterContext context) { - return new JSONObject(entry.toMap()); + public String clientEntryToWire(Entry entry, EntryQuery query, ClientWireFormatterContext context) { + return new JSONObject(entry.toMap()).toString(); } @Override public Entry wireToClientEntry(Object result, EntryQuery query, ClientWireFormatterContext context) { - return new DefaultEntry(((JSONObject) result).toMap()); + return new DefaultEntry((new JSONObject((String) result)).toMap()); } diff --git a/parameters-basic/parameters-basic-wireformat-json/src/main/java/be/kwakeroni/parameters/basic/wireformat/json/DefaultEntry.java b/parameters-basic/parameters-basic-wireformat-json/src/main/java/be/kwakeroni/parameters/basic/wireformat/json/DefaultEntry.java index 08523b7..b07497b 100644 --- a/parameters-basic/parameters-basic-wireformat-json/src/main/java/be/kwakeroni/parameters/basic/wireformat/json/DefaultEntry.java +++ b/parameters-basic/parameters-basic-wireformat-json/src/main/java/be/kwakeroni/parameters/basic/wireformat/json/DefaultEntry.java @@ -33,4 +33,8 @@ public boolean hasValue(Parameter parameter) { public Map toMap() { return this.values.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> String.valueOf(e.getValue()))); } + + public String toString() { + return values.toString(); + } } diff --git a/parameters-basic/parameters-basic-wireformat-json/src/test/java/TestBasicJsonWireFormatterAsClient.java b/parameters-basic/parameters-basic-wireformat-json/src/test/java/TestBasicJsonWireFormatterAsClient.java index a9cfe42..89f9ccc 100644 --- a/parameters-basic/parameters-basic-wireformat-json/src/test/java/TestBasicJsonWireFormatterAsClient.java +++ b/parameters-basic/parameters-basic-wireformat-json/src/test/java/TestBasicJsonWireFormatterAsClient.java @@ -99,8 +99,8 @@ public void testClientEntryToWire() { Object wireEntry = formatter.clientEntryToWire(entry, entryQuery, context); - assertThat(wireEntry).isInstanceOf(JSONObject.class); - JSONObject jsonEntry = (JSONObject) wireEntry; + assertThat(wireEntry).isInstanceOf(String.class); + JSONObject jsonEntry = new JSONObject((String) wireEntry); assertThat(jsonEntry.get("one")).isEqualTo("111"); assertThat(jsonEntry.get("two")).isEqualTo("22"); @@ -118,7 +118,7 @@ public void testWireToClientEntry() { .put("1", "one") .put("2", "zwei"); - Entry clientEntry = formatter.wireToClientEntry(jsonEntry, entryQuery, context); + Entry clientEntry = formatter.wireToClientEntry(jsonEntry.toString(), entryQuery, context); assertThat(clientEntry.getValue(parameter).get()).isEqualTo("one"); assertThat(clientEntry.getValue(parameter2).get()).isEqualTo("zwei"); diff --git a/parameters-client/parameters-client-rest/src/main/java/be/kwakeroni/parameters/client/rest/RestBusinessParametersClient.java b/parameters-client/parameters-client-rest/src/main/java/be/kwakeroni/parameters/client/rest/RestBusinessParametersClient.java index 5717fba..270d0ad 100644 --- a/parameters-client/parameters-client-rest/src/main/java/be/kwakeroni/parameters/client/rest/RestBusinessParametersClient.java +++ b/parameters-client/parameters-client-rest/src/main/java/be/kwakeroni/parameters/client/rest/RestBusinessParametersClient.java @@ -16,6 +16,8 @@ import java.util.Objects; import java.util.Optional; +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; + public class RestBusinessParametersClient implements WritableBusinessParameters { private static Logger LOG = LoggerFactory.getLogger(RestBusinessParametersClient.class); @@ -31,12 +33,16 @@ public RestBusinessParametersClient(String url, ClientWireFormatterContext conte } private String normalizePath(String path) { - if (path.endsWith("/")) { - path = path.substring(0, path.length() - 1); + if (!path.endsWith("/")) { + path = path + "/"; } return path; } + private WebResource resource(String path) { + return this.resource.path(path); + } + @Override public Optional get(ParameterGroup group, Query query) { @@ -45,9 +51,14 @@ public Optional get(ParameterGroup group, Query Objects.requireNonNull(query, "query"); String external = externalize(query); - ClientResponse response = this.resource.path("/" + group.getName() + "/query").post(ClientResponse.class, external); - return internalizeResult(query, process(response, String.class)); + WebResource resource = resource("/" + group.getName() + "/query"); + ClientResponse response = resource.type(APPLICATION_JSON).post(ClientResponse.class, external); + Optional result = process(resource, response, String.class) + .flatMap(extValue -> internalizeResult(query, extValue)); + + LOG.info("\n Query " + external + "\n Result " + result); + return result; } @Override @@ -62,9 +73,9 @@ public void set(ParameterGroup group, Query .put("value", externalizeValue(query, value)); - ClientResponse response = this.resource.path("/" + group.getName() + "/update").post(ClientResponse.class, request.toString()); - - process(response); + WebResource resource = resource("/" + group.getName() + "/update"); + ClientResponse response = resource.type(APPLICATION_JSON).post(ClientResponse.class, request.toString()); + process(resource, response); } @Override @@ -75,9 +86,9 @@ public void addEntry(ParameterGroup group, Entry entry) { JSONObject request = new JSONObject(entry.toMap()); - ClientResponse response = this.resource.path("/" + group.getName()).post(ClientResponse.class, request.toString()); - - process(response); + WebResource resource = resource("/" + group.getName()); + ClientResponse response = resource.type(APPLICATION_JSON).post(ClientResponse.class, request.toString()); + process(resource, response); } private String externalize(Query query) { @@ -102,24 +113,38 @@ private Optional internalizeResult(Query query, String value) { return query.internalizeResult(value, this.context); } - private T process(ClientResponse response, Class type) { - return process(response).getEntity(type); + private Optional process(WebResource resource, ClientResponse response, Class type) { + return process(resource.getURI().toString(), response, type); } - private ClientResponse process(ClientResponse response) { + private Optional process(String url, ClientResponse response, Class type) { + return getEntity(process(url, response), type); + } + + private ClientResponse process(WebResource resource, ClientResponse response) { + return process(resource.getURI().toString(), response); + } + + private ClientResponse process(String url, ClientResponse response) { switch (response.getStatusInfo().getFamily()) { case CLIENT_ERROR: - throw new IllegalArgumentException("Error response from Business Parameters REST service: status=" + response.getStatus() + " message=" + response.getEntity(String.class)); + throw new IllegalArgumentException("Error response from Business Parameters REST service: url=" + url + " status=" + response.getStatus() + " message=" + response.getEntity(String.class)); case SERVER_ERROR: - throw new IllegalStateException("Error response from Business Parameters REST service: status=" + response.getStatus() + " message=" + response.getEntity(String.class)); + throw new IllegalStateException("Error response from Business Parameters REST service: url=" + url + " status=" + response.getStatus() + " message=" + response.getEntity(String.class)); case OTHER: - throw new IllegalStateException("Unknown response from Business Parameters REST service: status=" + response.getStatus() + " message=" + response.getEntity(String.class)); + throw new IllegalStateException("Unknown response from Business Parameters REST service: url=" + url + " status=" + response.getStatus() + " message=" + response.getEntity(String.class)); case INFORMATIONAL: case REDIRECTION: - LOG.warn("Unexpected response: status=" + response.getStatus() + " entity=" + response.getEntity(String.class)); + LOG.warn("Unexpected response: url=" + url + " status=" + response.getStatus() + " entity=" + response.getEntity(String.class)); case SUCCESSFUL: return response; } return response; } + + private Optional getEntity(ClientResponse response, Class type) { + return Optional.of(response) + .filter(r -> r.getStatus() != 204) + .map(r -> r.getEntity(type)); + } } diff --git a/parameters-core/parameters-test-support/src/test/java/be/kwakeroni/test/extension/ExtensionSupportTest.java b/parameters-core/parameters-test-support/src/test/java/be/kwakeroni/test/extension/ExtensionSupportTest.java index b6b69c1..c3e9b2b 100644 --- a/parameters-core/parameters-test-support/src/test/java/be/kwakeroni/test/extension/ExtensionSupportTest.java +++ b/parameters-core/parameters-test-support/src/test/java/be/kwakeroni/test/extension/ExtensionSupportTest.java @@ -43,7 +43,7 @@ void getsFields(TestExtension extension) { assertThat( extension.getFields(this) .map(ExtensionSupportTest::toString) - ).containsExactlyInAnyOrder("ExtensionSupportTest:oneField", "ExtensionSupportTest:secondField"); + ).contains("ExtensionSupportTest:oneField", "ExtensionSupportTest:secondField"); } diff --git a/petshop/petshop-application/src/main/java/be/kwakeroni/parameters/petshop/DemoApplication.java b/petshop/petshop-application/src/main/java/be/kwakeroni/parameters/petshop/DemoApplication.java new file mode 100644 index 0000000..99ce53e --- /dev/null +++ b/petshop/petshop-application/src/main/java/be/kwakeroni/parameters/petshop/DemoApplication.java @@ -0,0 +1,59 @@ +package be.kwakeroni.parameters.petshop; + +import be.kwakeroni.parameters.app.Application; +import be.kwakeroni.parameters.app.support.MainWaiter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Properties; + +public class DemoApplication { + + private static final Logger LOG = LoggerFactory.getLogger(PetshopApplication.class); + + public static void main(String[] args) throws Exception { + + initLogging(); + + Properties properties = new Properties(); + properties.load(PetshopApplication.class.getResourceAsStream("/petshop.properties")); + initDemoEnvironment(properties); + + + + final PetshopApplication petshop = PetshopApplication.create(properties) + .orElseThrow(() -> new IllegalStateException("Unable to start PetshopApplication")); + + final Application app = Application.create(properties) + .orElseThrow(() -> new IllegalStateException("Unable to start Business Parameters Application")); + + try (AutoCloseable closeableApp = app.start(); + AutoCloseable closeablePetshop = petshop.start()) { + MainWaiter.waitForExit(); + } + + } + + private static void initLogging() { + System.out.println("log4j.configuration=" + System.getProperty("log4j.configuration")); + if (System.getProperty("log4j.configuration") == null) { + if (Thread.currentThread().getContextClassLoader().getResource("log4j.properties") == null) { + System.setProperty("log4j.configuration", "log4j.fallback.properties"); + } + } + } + + + private static void initDemoEnvironment(Properties properties) throws IOException { + Path storageFolder = Paths.get(properties.getProperty("inmemory.storage.folder")); + if (!Files.exists(storageFolder)){ + LOG.info("Creating demo storage folder at: " + storageFolder.toAbsolutePath()); + Files.createDirectories(storageFolder); + } + } + +} diff --git a/petshop/petshop-application/src/main/java/be/kwakeroni/parameters/petshop/OldPetshopApplication.java b/petshop/petshop-application/src/main/java/be/kwakeroni/parameters/petshop/OldPetshopApplication.java deleted file mode 100644 index 510c13c..0000000 --- a/petshop/petshop-application/src/main/java/be/kwakeroni/parameters/petshop/OldPetshopApplication.java +++ /dev/null @@ -1,165 +0,0 @@ -package be.kwakeroni.parameters.petshop; - -import be.kwakeroni.parameters.client.api.BusinessParameters; -import be.kwakeroni.parameters.client.api.factory.BusinessParametersFactory; -import be.kwakeroni.parameters.petshop.rest.PetshopRestService; -import be.kwakeroni.parameters.petshop.service.AnimalCatalog; -import be.kwakeroni.parameters.petshop.service.ContactService; -import be.kwakeroni.parameters.petshop.service.PriceCalculator; -import com.sun.jersey.api.container.ContainerFactory; -import com.sun.jersey.api.container.httpserver.HttpServerFactory; -import com.sun.jersey.api.core.ApplicationAdapter; -import com.sun.jersey.api.core.ResourceConfig; -import com.sun.net.httpserver.HttpHandler; -import com.sun.net.httpserver.HttpServer; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.core.Application; -import javax.ws.rs.core.Response; -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.net.URL; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.Map; -import java.util.Properties; -import java.util.ServiceLoader; -import java.util.Set; -import java.util.function.Function; -import java.util.stream.Collectors; - -/** - * Created by kwakeroni on 07/11/17. - */ -public class OldPetshopApplication { - - - private OldPetshopApplication() { - } - - private static PetshopRestService createPetshopRestService(Map properties) { - BusinessParameters parameters = createBusinessParameters(properties); - return new PetshopRestService( - new AnimalCatalog(parameters), - new PriceCalculator(parameters), - new ContactService(parameters)); - } - - public static void main(String[] args) throws Exception { - Properties properties = new Properties(); - properties.load(OldPetshopApplication.class.getResourceAsStream("/petshop.properties")); - Map propertyMap = properties.stringPropertyNames().stream().collect(Collectors.toMap(Function.identity(), properties::getProperty)); - - try ( - Server petshop = new Server(8081, "/", - createPetshopRestService(propertyMap), - new PetshopWebAppService() - ); - ) { - petshop.start(); - System.out.println("Enter 'q' to stop server."); - boolean running = true; - while (running) { - if ('q' == System.in.read()) { - running = false; - } - } - } - - } - - private static class Server implements AutoCloseable { - - private HttpServer server; - - public Server(int port, String root, Object... resources) throws IOException { - ResourceConfig config = new ApplicationAdapter(ofSingletons(resources)); - config.setPropertiesAndFeatures(Collections.singletonMap("com.sun.jersey.api.json.POJOMappingFeature", true)); - - this.server = HttpServerFactory.create("http://127.0.0.1:" + port + root, - ContainerFactory.createContainer(HttpHandler.class, config, null)); - } - - public void start() { - this.server.start(); - } - - @Override - public void close() throws Exception { - if (this.server != null) this.server.stop(0); - - } - } - - private static BusinessParameters createBusinessParameters(Map properties) { - return ServiceLoader.load(BusinessParametersFactory.class).iterator().next() - .getInstance(properties); - } - - private static Application ofSingletons(Object... singletons) { - return new Application() { - @Override - public Set getSingletons() { - return new HashSet<>(Arrays.asList(singletons)); - } - }; - } - - - public static abstract class AbstractWebAppService { - - private final String resourcePath; - private final String indexPage; - - public AbstractWebAppService(String resourcePath, String indexPage) { - this.resourcePath = resourcePath; - this.indexPage = indexPage; - } - - @GET - @Path("/") - public Response root() throws Exception { - return Response.seeOther(new URI(indexPage)).build(); - } - - @GET - @Path("{path:.*}") - public Response get(@PathParam("path") String path) throws Exception { - if (path == null || path.isEmpty() || "/".equals(path)) { - path = "index.html"; - } - - String webPath = resourcePath + "/" + path; - URL resource = OldPetshopApplication.class.getResource(webPath); - - if (resource != null) { - File file = new File(resource.toURI()); - - return Response.ok(file) - // .header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"" ) //optional - .build(); - } else { - System.out.println("Resource not found: " + webPath); - return Response.status(404).build(); - } - } - } - - @Path("/petshop") - public static class PetshopWebAppService extends AbstractWebAppService { - public PetshopWebAppService() { - super("/petshop-webapp", "petshop/index.html"); - } - } - - @Path("/web") - public static class ParametersWebAppService extends AbstractWebAppService { - public ParametersWebAppService() { - super("/parameters-webapp", "web/index.html"); - } - } -} diff --git a/petshop/petshop-application/src/main/java/be/kwakeroni/parameters/petshop/PetshopApplication.java b/petshop/petshop-application/src/main/java/be/kwakeroni/parameters/petshop/PetshopApplication.java index b8456d5..41d7edf 100644 --- a/petshop/petshop-application/src/main/java/be/kwakeroni/parameters/petshop/PetshopApplication.java +++ b/petshop/petshop-application/src/main/java/be/kwakeroni/parameters/petshop/PetshopApplication.java @@ -1,5 +1,6 @@ package be.kwakeroni.parameters.petshop; +import be.kwakeroni.parameters.app.support.MainWaiter; import be.kwakeroni.parameters.app.support.SimpleRestServer; import be.kwakeroni.parameters.app.support.StaticContent; import be.kwakeroni.parameters.app.support.StaticContentFactory; @@ -14,7 +15,6 @@ import javax.ws.rs.Path; import java.io.IOException; import java.io.InputStream; -import java.io.UncheckedIOException; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collection; @@ -32,14 +32,33 @@ public class PetshopApplication { @SuppressWarnings("WeakerAccess") public static final String DEFAULT_CONTEXT_PATH = ""; + private final Server server; + public static void main(String[] args) throws Exception { initLogging(); + Optional app = create(args); + if (app.isPresent()) { + try (AutoCloseable closeable = app.get().start()) { + MainWaiter.waitForExit(); + } + } + } - createServer(args) - .ifPresent(PetshopApplication::start); + public static Optional create(String... args) throws IOException { + return createServer(args) + .map(PetshopApplication::new); + } + + public static Optional create(Properties configurationProperties) throws IOException { + return createServer(configurationProperties) + .map(PetshopApplication::new); + } + private PetshopApplication(Server server) { + this.server = server; } + private static void initLogging() { System.out.println("log4j.configuration=" + System.getProperty("log4j.configuration")); if (System.getProperty("log4j.configuration") == null) { @@ -49,25 +68,19 @@ private static void initLogging() { } } - private static void start(Server resource) { - try (Server server = resource) { - server.start(); - - while (true) { - // Thread.onSpinWait(); - } - - } catch (IOException exc) { - throw new UncheckedIOException(exc); - } + public AutoCloseable start() throws IOException { + this.server.start(); + return this.server; } - - static Optional createServer(String[] args) throws IOException { + static Optional createServer(String... args) throws IOException { Properties properties = new Properties(); - properties.load(OldPetshopApplication.class.getResourceAsStream("/petshop.properties")); - Map propertyMap = properties.stringPropertyNames().stream().collect(Collectors.toMap(Function.identity(), properties::getProperty)); + properties.load(PetshopApplication.class.getResourceAsStream("/petshop.properties")); + return createServer(properties); + } + static Optional createServer(Properties properties) throws IOException { + Map propertyMap = properties.stringPropertyNames().stream().collect(Collectors.toMap(Function.identity(), properties::getProperty)); return Optional.of(new Server(propertyMap)); } diff --git a/petshop/petshop-application/src/main/resources/petshop.properties b/petshop/petshop-application/src/main/resources/petshop.properties index 0942423..0b91d02 100644 --- a/petshop/petshop-application/src/main/resources/petshop.properties +++ b/petshop/petshop-application/src/main/resources/petshop.properties @@ -1,2 +1,5 @@ -inmemory.storage.folder=${project.basedir}/data -parameters.rest.url=http://localhost:9988/failure \ No newline at end of file +server.workDir=./work +server.port=8080 +server.contextPath=parameters +parameters.rest.url=http://localhost:8080/parameters/client +inmemory.storage.folder=./data