Search in sources :

Example 91 with Injector

use of com.google.inject.Injector in project camel by apache.

the class ConciseGuiceRouteTest method testGuice.

@SuppressWarnings("unchecked")
@Test
public void testGuice() throws Exception {
    // lets disable resource injection to avoid JNDI being used
    Injector injector = Guice.createInjector(new CamelModuleWithRouteTypes(MyRouteInstaller.class, MyHardcodeRoute.class));
    GuiceTest.assertCamelContextRunningThenCloseInjector(injector);
}
Also used : Injector(com.google.inject.Injector) Test(org.junit.Test)

Example 92 with Injector

use of com.google.inject.Injector in project camel by apache.

the class EndpointInjectionTest method testGuice.

@Test
public void testGuice() throws Exception {
    Injector injector = Guice.createInjector(new MyModule());
    MyBean bean = injector.getInstance(MyBean.class);
    assertNotNull("bean.endpoint", bean.endpoint);
    assertEquals("bean.endpoint.uri", "mock://foo", bean.endpoint.getEndpointUri());
    GuiceTest.assertCamelContextRunningThenCloseInjector(injector);
}
Also used : Injector(com.google.inject.Injector) Test(org.junit.Test)

Example 93 with Injector

use of com.google.inject.Injector in project camel by apache.

the class FileEndpointReferenceRouteTest method runTest.

@Test
public void runTest() throws Exception {
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.PROVIDER_URL, GuiceInitialContextFactory.class.getName());
    env.put(Injectors.MODULE_CLASS_NAMES, MyModule.class.getName());
    InitialContext context = new InitialContext(env);
    Injector injector = (Injector) context.lookup(Injector.class.getName());
    assertNotNull("Found injector", injector);
    Object value = context.lookup("fileFilter");
    assertNotNull("Should have found a value for foo!", value);
    assertCamelContextRunningThenCloseInjector(injector);
}
Also used : Hashtable(java.util.Hashtable) Injector(com.google.inject.Injector) GuiceInitialContextFactory(org.apache.camel.guice.jndi.GuiceInitialContextFactory) InitialContext(javax.naming.InitialContext) Test(org.junit.Test)

Example 94 with Injector

use of com.google.inject.Injector in project presto by prestodb.

the class PrestoVerifier method run.

public int run(String[] args) throws Exception {
    if (args.length > 0) {
        System.setProperty("config", args[0]);
    }
    ImmutableList.Builder<Module> builder = ImmutableList.<Module>builder().add(new PrestoVerifierModule()).addAll(getAdditionalModules());
    Bootstrap app = new Bootstrap(builder.build());
    Injector injector = app.strictConfig().initialize();
    try {
        VerifierConfig config = injector.getInstance(VerifierConfig.class);
        injector.injectMembers(this);
        Set<String> supportedEventClients = injector.getInstance(Key.get(new TypeLiteral<Set<String>>() {
        }, Names.named(SUPPORTED_EVENT_CLIENTS)));
        for (String clientType : config.getEventClients()) {
            checkArgument(supportedEventClients.contains(clientType), "Unsupported event client: %s", clientType);
        }
        Set<EventClient> eventClients = injector.getInstance(Key.get(new TypeLiteral<Set<EventClient>>() {
        }));
        VerifierDao dao = new DBI(config.getQueryDatabase()).onDemand(VerifierDao.class);
        ImmutableList.Builder<QueryPair> queriesBuilder = ImmutableList.builder();
        for (String suite : config.getSuites()) {
            queriesBuilder.addAll(dao.getQueriesBySuite(suite, config.getMaxQueries()));
        }
        List<QueryPair> queries = queriesBuilder.build();
        queries = applyOverrides(config, queries);
        queries = filterQueryTypes(new SqlParser(getParserOptions()), config, queries);
        queries = filterQueries(queries);
        if (config.getShadowWrites()) {
            Sets.SetView<QueryType> allowedTypes = Sets.union(config.getTestQueryTypes(), config.getControlQueryTypes());
            checkArgument(!Sets.intersection(allowedTypes, ImmutableSet.of(CREATE, MODIFY)).isEmpty(), "CREATE or MODIFY queries must be allowed in test or control to use write shadowing");
            queries = rewriteQueries(new SqlParser(getParserOptions()), config, queries);
        }
        // Load jdbc drivers if needed
        if (config.getAdditionalJdbcDriverPath() != null) {
            List<URL> urlList = getUrls(config.getAdditionalJdbcDriverPath());
            URL[] urls = new URL[urlList.size()];
            urlList.toArray(urls);
            if (config.getTestJdbcDriverName() != null) {
                loadJdbcDriver(urls, config.getTestJdbcDriverName());
            }
            if (config.getControlJdbcDriverName() != null) {
                loadJdbcDriver(urls, config.getControlJdbcDriverName());
            }
        }
        // TODO: construct this with Guice
        Verifier verifier = new Verifier(System.out, config, eventClients);
        return verifier.run(queries);
    } finally {
        injector.getInstance(LifeCycleManager.class).stop();
    }
}
Also used : ImmutableCollectors.toImmutableList(com.facebook.presto.util.ImmutableCollectors.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) DBI(org.skife.jdbi.v2.DBI) URL(java.net.URL) TypeLiteral(com.google.inject.TypeLiteral) Injector(com.google.inject.Injector) Sets(com.google.common.collect.Sets) Bootstrap(io.airlift.bootstrap.Bootstrap) SqlParser(com.facebook.presto.sql.parser.SqlParser) EventClient(io.airlift.event.client.EventClient) LifeCycleManager(io.airlift.bootstrap.LifeCycleManager) Module(com.google.inject.Module)

Example 95 with Injector

use of com.google.inject.Injector in project acceptance-test-harness by jenkinsci.

the class MockUpdateCenter method ensureRunning.

public void ensureRunning() {
    if (original != null) {
        return;
    }
    // TODO this will likely not work on arbitrary controllers, so perhaps limit to the default WinstoneController
    Jenkins jenkins = injector.getInstance(Jenkins.class);
    List<String> sites = new UpdateCenter(jenkins).getJson("tree=sites[url]").findValuesAsText("url");
    if (sites.size() != 1) {
        // TODO ideally it would rather delegate to all of them, but that implies deprecating CachedUpdateCenterMetadataLoader.url and using whatever site(s) Jenkins itself specifies
        LOGGER.log(Level.WARNING, "found an unexpected number of update sites: {0}", sites);
        return;
    }
    UpdateCenterMetadata ucm;
    try {
        ucm = ucmd.get(jenkins);
    } catch (IOException x) {
        LOGGER.log(Level.WARNING, "cannot load data for mock update center", x);
        return;
    }
    JSONObject all;
    try {
        all = new JSONObject(ucm.originalJSON);
        all.remove("signature");
        JSONObject plugins = all.getJSONObject("plugins");
        LOGGER.info(() -> "editing JSON with " + plugins.length() + " plugins to reflect " + ucm.plugins.size() + " possible overrides");
        for (PluginMetadata meta : ucm.plugins.values()) {
            String name = meta.getName();
            String version = meta.getVersion();
            JSONObject plugin = plugins.optJSONObject(name);
            if (plugin == null) {
                LOGGER.log(Level.INFO, "adding plugin {0}", name);
                plugin = new JSONObject().accumulate("name", name);
                plugins.put(name, plugin);
            }
            plugin.put("url", name + ".hpi");
            updating(plugin, "version", version);
            updating(plugin, "gav", meta.gav);
            updating(plugin, "requiredCore", meta.requiredCore().toString());
            updating(plugin, "dependencies", new JSONArray(meta.getDependencies().stream().map(d -> {
                try {
                    return new JSONObject().accumulate("name", d.name).accumulate("version", d.version).accumulate("optional", d.optional);
                } catch (JSONException x) {
                    throw new AssertionError(x);
                }
            }).collect(Collectors.toList())));
            plugin.remove("sha1");
        }
    } catch (JSONException x) {
        LOGGER.log(Level.WARNING, "cannot prepare mock update center", x);
        return;
    }
    HttpProcessor proc = HttpProcessorBuilder.create().add(new ResponseServer("MockUpdateCenter")).add(new ResponseContent()).add(new RequestConnControl()).build();
    UriHttpRequestHandlerMapper handlerMapper = new UriHttpRequestHandlerMapper();
    String json = "updateCenter.post(\n" + all + "\n);";
    handlerMapper.register("/update-center.json", (HttpRequest request, HttpResponse response, HttpContext context) -> {
        response.setStatusCode(HttpStatus.SC_OK);
        response.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
    });
    handlerMapper.register("*.hpi", (HttpRequest request, HttpResponse response, HttpContext context) -> {
        String plugin = request.getRequestLine().getUri().replaceFirst("^/(.+)[.]hpi$", "$1");
        PluginMetadata meta = ucm.plugins.get(plugin);
        if (meta == null) {
            LOGGER.log(Level.WARNING, "no such plugin {0}", plugin);
            response.setStatusCode(HttpStatus.SC_NOT_FOUND);
            return;
        }
        File local = meta.resolve(injector, meta.getVersion());
        LOGGER.log(Level.INFO, "serving {0}", local);
        response.setStatusCode(HttpStatus.SC_OK);
        response.setEntity(new FileEntity(local));
    });
    handlerMapper.register("*", (HttpRequest request, HttpResponse response, HttpContext context) -> {
        String location = original.replace("/update-center.json", request.getRequestLine().getUri());
        LOGGER.log(Level.INFO, "redirect to {0}", location);
        /* TODO for some reason DownloadService.loadJSONHTML does not seem to process the redirect, despite calling setInstanceFollowRedirects(true):
            response.setStatusCode(HttpStatus.SC_MOVED_TEMPORARILY);
            response.setHeader("Location", location);
             */
        HttpURLConnection uc = (HttpURLConnection) new URL(location).openConnection();
        uc.setInstanceFollowRedirects(true);
        // TODO consider caching these downloads locally like CachedUpdateCenterMetadataLoader does for the main update-center.json
        byte[] data = IOUtils.toByteArray(uc);
        String contentType = uc.getContentType();
        response.setStatusCode(HttpStatus.SC_OK);
        response.setEntity(new ByteArrayEntity(data, ContentType.create(contentType)));
    });
    server = ServerBootstrap.bootstrap().setHttpProcessor(proc).setHandlerMapper(handlerMapper).setExceptionLogger(serverExceptionHandler()).create();
    try {
        server.start();
    } catch (IOException x) {
        LOGGER.log(Level.WARNING, "cannot start mock update center", x);
        return;
    }
    original = sites.get(0);
    // TODO figure out how to deal with Docker-based controllers which would need to have an IP address for the host
    String override = "http://" + server.getInetAddress().getHostAddress() + ":" + server.getLocalPort() + "/update-center.json";
    LOGGER.log(Level.INFO, "replacing update site {0} with {1}", new Object[] { original, override });
    jenkins.runScript("DownloadService.signatureCheck = false; Jenkins.instance.updateCenter.sites.replaceBy([new UpdateSite(UpdateCenter.ID_DEFAULT, '%s')])", override);
}
Also used : HttpURLConnection(java.net.HttpURLConnection) UriHttpRequestHandlerMapper(org.apache.http.protocol.UriHttpRequestHandlerMapper) AutoCleaned(org.jenkinsci.test.acceptance.guice.AutoCleaned) URL(java.net.URL) Inject(com.google.inject.Inject) HttpStatus(org.apache.http.HttpStatus) ExceptionLogger(org.apache.http.ExceptionLogger) RequestConnControl(org.apache.http.protocol.RequestConnControl) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) Level(java.util.logging.Level) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) HttpProcessorBuilder(org.apache.http.protocol.HttpProcessorBuilder) TestScope(org.jenkinsci.test.acceptance.guice.TestScope) ResponseContent(org.apache.http.protocol.ResponseContent) Jenkins(org.jenkinsci.test.acceptance.po.Jenkins) ContentType(org.apache.http.entity.ContentType) FileEntity(org.apache.http.entity.FileEntity) StringEntity(org.apache.http.entity.StringEntity) ServerBootstrap(org.apache.http.impl.bootstrap.ServerBootstrap) IOException(java.io.IOException) HttpProcessor(org.apache.http.protocol.HttpProcessor) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) HttpRequest(org.apache.http.HttpRequest) HttpServer(org.apache.http.impl.bootstrap.HttpServer) File(java.io.File) ResponseServer(org.apache.http.protocol.ResponseServer) Injector(com.google.inject.Injector) TimeUnit(java.util.concurrent.TimeUnit) IOUtils(org.apache.commons.io.IOUtils) List(java.util.List) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) ConnectionClosedException(org.apache.http.ConnectionClosedException) UpdateCenter(org.jenkinsci.test.acceptance.po.UpdateCenter) JSONArray(org.json.JSONArray) ResponseContent(org.apache.http.protocol.ResponseContent) UpdateCenter(org.jenkinsci.test.acceptance.po.UpdateCenter) HttpProcessor(org.apache.http.protocol.HttpProcessor) URL(java.net.URL) StringEntity(org.apache.http.entity.StringEntity) HttpURLConnection(java.net.HttpURLConnection) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) UriHttpRequestHandlerMapper(org.apache.http.protocol.UriHttpRequestHandlerMapper) HttpRequest(org.apache.http.HttpRequest) FileEntity(org.apache.http.entity.FileEntity) JSONArray(org.json.JSONArray) HttpContext(org.apache.http.protocol.HttpContext) JSONException(org.json.JSONException) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) Jenkins(org.jenkinsci.test.acceptance.po.Jenkins) RequestConnControl(org.apache.http.protocol.RequestConnControl) JSONObject(org.json.JSONObject) File(java.io.File) ResponseServer(org.apache.http.protocol.ResponseServer)

Aggregations

Injector (com.google.inject.Injector)2159 AbstractModule (com.google.inject.AbstractModule)623 Test (org.junit.Test)513 Module (com.google.inject.Module)364 Test (org.testng.annotations.Test)131 Before (org.junit.Before)116 Binder (com.google.inject.Binder)114 Properties (java.util.Properties)110 Key (com.google.inject.Key)84 Map (java.util.Map)78 HttpServletRequest (javax.servlet.http.HttpServletRequest)78 Provider (com.google.inject.Provider)74 IOException (java.io.IOException)71 TypeLiteral (com.google.inject.TypeLiteral)70 Set (java.util.Set)64 BeforeClass (org.junit.BeforeClass)61 File (java.io.File)60 CConfiguration (co.cask.cdap.common.conf.CConfiguration)55 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)55 PrivateModule (com.google.inject.PrivateModule)55