public static String buildStatusResponse() { return "{\n \"status\":\"ok\"\n \"version\":\"" + MetaUtil.readVersion() + "\"\n}"; }
static WeightedAcceptEntry parse(String weightAndContentType) { final WeightedAcceptEntry entry = new WeightedAcceptEntry(); // split to obtain weight final String[] sEntry = weightAndContentType.split(";"); entry.contentType = sEntry[0]; entry.weight = (sEntry.length > 1 && sEntry[1].toLowerCase().startsWith("q=") ? Float.valueOf(sEntry[1].substring(2)) : 0); return entry; } }
public static Properties readMetaProperties() { if (isNull(metaProperties)) { metaProperties = new Properties(); try (InputStream properties = getClassLoader().getResourceAsStream(METADATA_PROPERTIES)) { if (!isNull(properties)) { metaProperties.load(properties); } } catch (IOException e) { LOGGER.warn("Error reading metadata properties from {} - continuing", METADATA_PROPERTIES, e); } } return metaProperties; }
router.get(path + "/:tableName/:recordId/").handler(handleAsync(routingContext -> { final String tableName = routingContext.request().getParam("tableName"); final String recordId = routingContext.request().getParam("recordId"); final Optional<JsonObject> result = FileUtil.findRow(config.getIdField(), recordInfo.getRecordId(), results);
@Override public void configureRoutes(Router router) { router.get("/example").handler(handleAsync(routingContext -> routingContext.response().setStatusCode(HttpUtil.HTTP_OK).end())); }
/** * Read the content types accepted by the requesting client, ordered by their weighting. * * @param routingContext the Vert.x routing context * @return the ordered content types */ public static List<String> readAcceptedContentTypes(RoutingContext routingContext) { return readAcceptedContentTypes(routingContext.request().getHeader("Accept")); }
@Override public void start(Future<Void> startFuture) throws Exception { LOGGER.debug("Initialising mock server"); new Imposter().start(); InjectorUtil.getInjector().injectMembers(this); startServer(startFuture); }
private void startServer(String[] originalArgs) { InjectorUtil.create(new BootstrapModule()).injectMembers(this); if (isNull(pluginClassNames) || 0 == pluginClassNames.length) { LOGGER.debug("No plugins specified - attempting to load defaults"); // check for list of comma-separated plugin classes to load if none specified pluginClassNames = ofNullable(MetaUtil.readMetaProperties().getProperty("plugins")) .map(plugin -> plugin.split(",")) .orElse(new String[0]); } final Map<String, String> splitArgs = Arrays.stream(ofNullable(pluginArgs).orElse(new String[0])) .map(arg -> arg.split("=")) .collect(Collectors.toMap(splitArg -> splitArg[0], splitArg -> splitArg[1])); imposterConfig.setConfigDirs(configDirs); imposterConfig.setPluginClassNames(pluginClassNames); imposterConfig.setListenPort(listenPort); imposterConfig.setHost(host); imposterConfig.setServerUrl(serverUrl); imposterConfig.setTlsEnabled(tlsEnabled); imposterConfig.setKeystorePath(keystorePath); imposterConfig.setKeystorePassword(keystorePassword); imposterConfig.setPluginArgs(splitArgs); final List<String> args = Lists.newArrayList(originalArgs); args.add(0, "run"); args.add(1, ImposterVerticle.class.getCanonicalName()); super.dispatch(args.toArray(new String[args.size()])); }
@Before public void setUp(TestContext testContext) throws Exception { super.setUp(testContext); // set up trust store for TLS System.setProperty("javax.net.ssl.trustStore", CryptoUtil.getDefaultKeystore(SfdcPluginImplTest.class).toString()); System.setProperty("javax.net.ssl.trustStorePassword", CryptoUtil.DEFAULT_KEYSTORE_PASSWORD); System.setProperty("javax.net.ssl.trustStoreType", "JKS"); // for localhost testing only javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier( (hostname, sslSession) -> hostname.equals("localhost")); }
@Before public void setUp(TestContext testContext) throws Exception { final Async async = testContext.async(); listenPort = findFreePort(); // simulate ImposterLauncher injector bootstrap final ImposterConfig imposterConfig = InjectorUtil.create(new BootstrapModule()).getInstance(ImposterConfig.class); configure(imposterConfig); rule.vertx().deployVerticle(ImposterVerticle.class.getCanonicalName(), completion -> { if (completion.succeeded()) { async.complete(); } else { testContext.fail(completion.cause()); } }); }
/** * Main entry point. * * @param args the user command line arguments. */ public static void main(String[] args) { LogUtil.configureLogging(System.getProperty(LogUtil.PROPERTY_LOG_LEVEL, "DEBUG")); new ImposterLauncher().dispatch(args); }
public void start() { InjectorUtil.createChildInjector(getModules()).injectMembers(this); // server config processConfiguration(); // load and configure plugins final Map<String, List<File>> pluginConfigs = loadPluginConfigs(imposterConfig.getConfigDirs()); instantiatePlugins(imposterConfig.getPluginClassNames(), pluginConfigs); configurePlugins(pluginConfigs); }
private Router configureRoutes() { final Router router = Router.router(vertx); router.route().handler(new BodyHandlerImpl()); // status check to indicate when server is up router.get("/system/status").handler(routingContext -> routingContext.response() .putHeader(HttpUtil.CONTENT_TYPE, HttpUtil.CONTENT_TYPE_JSON) .end(HttpUtil.buildStatusResponse())); pluginManager.getPlugins().forEach(plugin -> plugin.configureRoutes(router)); return router; } }
/** * Can be a PATCH or a POST request (with query parameter '_HttpMethod=PATCH'). * * @return */ private Handler<RoutingContext> handleUpdateRequest() { return handleAsync(routingContext -> { final String sObjectName = routingContext.request().getParam("sObjectName"); final String sObjectId = routingContext.request().getParam("sObjectId"); final JsonObject sObject = routingContext.getBodyAsJson(); // SFDC work-around for HTTP clients that don't support PATCH if (!HttpMethod.PATCH.equals(routingContext.request().method()) && !"PATCH".equals(routingContext.request().getParam("_HttpMethod"))) { routingContext.fail(HttpUtil.HTTP_BAD_METHOD); return; } LOGGER.info("Received update request for {} with ID: {}: {}", sObjectName, sObjectId, sObject); routingContext.response() .putHeader(CONTENT_TYPE, CONTENT_TYPE_JSON) .setStatusCode(HttpUtil.HTTP_NO_CONTENT) .end(); }); }
@Test public void readAcceptedContentTypes() throws Exception { // note: provided out of order, but should be sorted by 'q' weight final String acceptHeader = "text/html; q=1.0, text/*; q=0.8, image/jpeg; q=0.5, image/gif; q=0.7, image/*; q=0.4, */*; q=0.1"; final List<String> actual = HttpUtil.readAcceptedContentTypes(acceptHeader); assertNotNull(actual); assertEquals(6, actual.size()); // check order assertEquals("text/html", actual.get(0)); assertEquals("text/*", actual.get(1)); assertEquals("image/gif", actual.get(2)); assertEquals("image/jpeg", actual.get(3)); assertEquals("image/*", actual.get(4)); assertEquals("*/*", actual.get(5)); } }
default void scriptHandler(C config, RoutingContext routingContext, Map<String, Object> additionalContext, Consumer<ResponseBehaviour> defaultBehaviourHandler) { final ResponseService responseService = InjectorUtil.getInjector().getInstance(ResponseService.class); try { final ResponseBehaviour responseBehaviour = responseService.getResponseBehaviour( routingContext, config, additionalContext, Collections.emptyMap()); if (ResponseBehaviourType.IMMEDIATE_RESPONSE.equals(responseBehaviour.getBehaviourType())) { routingContext.response() .setStatusCode(responseBehaviour.getStatusCode()) .end(); } else { // default behaviour defaultBehaviourHandler.accept(responseBehaviour); } } catch (Exception e) { routingContext.fail(e); } } }
private void printVersion() { System.out.println("Version: " + MetaUtil.readVersion()); }
@Before public void setUp(TestContext testContext) throws Exception { super.setUp(testContext); // set up trust store for TLS RestAssured.trustStore(CryptoUtil.getDefaultKeystore(ImposterVerticleTest.class).toFile(), CryptoUtil.DEFAULT_KEYSTORE_PASSWORD); RestAssured.baseURI = "https://" + HOST + ":" + getListenPort(); }
public static String readVersion() { if (isNull(version)) { try { final Enumeration<URL> manifests = getClassLoader().getResources(METADATA_MANIFEST); while (manifests.hasMoreElements() && isNull(version)) { try (final InputStream manifestStream = manifests.nextElement().openStream()) { final Manifest manifest = new Manifest(manifestStream); version = manifest.getMainAttributes().getValue(MANIFEST_VERSION_KEY); } } } catch (IOException ignored) { } version = Optional.ofNullable(version).orElse("unknown"); } return version; }
@Test public void testPluginLoadAndConfig(TestContext testContext) throws Exception { final PluginManager pluginManager = InjectorUtil.getInjector().getInstance(PluginManager.class); final TestPluginImpl plugin = pluginManager.getPlugin(TestPluginImpl.class.getCanonicalName()); testContext.assertNotNull(plugin); testContext.assertNotNull(plugin.getConfigs()); testContext.assertEquals(1, plugin.getConfigs().size()); final TestPluginConfig pluginConfig = plugin.getConfigs().get(0); testContext.assertEquals("/example", pluginConfig.getPath()); testContext.assertEquals("simple-plugin-data.json", pluginConfig.getResponseConfig().getStaticFile()); testContext.assertEquals("testValue", pluginConfig.getCustomProperty()); }