Example usage for org.springframework.boot.builder SpringApplicationBuilder SpringApplicationBuilder

List of usage examples for org.springframework.boot.builder SpringApplicationBuilder SpringApplicationBuilder

Introduction

In this page you can find the example usage for org.springframework.boot.builder SpringApplicationBuilder SpringApplicationBuilder.

Prototype

public SpringApplicationBuilder(Class<?>... sources) 

Source Link

Usage

From source file:org.springframework.cloud.config.server.environment.ConfigurableHttpConnectionFactoryIntegrationTests.java

@Test
public void authenticatedHttpProxy() throws Exception {
    String repoUrl = "https://myrepo/repo.git";
    new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE)
            .properties(gitProperties(repoUrl, AUTHENTICATED_HTTP_PROXY, null)).run();
    HttpClient httpClient = getHttpClientForUrl(repoUrl);
    this.expectedException.expectCause(allOf(instanceOf(UnknownHostException.class),
            hasProperty("message", containsString(AUTHENTICATED_HTTP_PROXY.getHost()))));

    makeRequest(httpClient, "http://somehost");
}

From source file:org.springframework.cloud.config.server.environment.ConfigurableHttpConnectionFactoryIntegrationTests.java

@Test
public void httpProxy() throws Exception {
    String repoUrl = "https://myrepo/repo.git";
    new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE)
            .properties(gitProperties(repoUrl, HTTP_PROXY, null)).run();
    HttpClient httpClient = getHttpClientForUrl(repoUrl);
    this.expectedException.expectCause(allOf(instanceOf(UnknownHostException.class),
            hasProperty("message", containsString(HTTP_PROXY.getHost()))));

    makeRequest(httpClient, "http://somehost");
}

From source file:org.springframework.cloud.config.server.environment.ConfigurableHttpConnectionFactoryIntegrationTests.java

@Test
public void httpProxy_placeholderUrl() throws Exception {
    new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE)
            .properties(gitProperties("https://myrepo/{placeholder}-repo.git", HTTP_PROXY, null)).run();
    HttpClient httpClient = getHttpClientForUrl("https://myrepo/someplaceholdervalue-repo.git");
    this.expectedException.expectCause(allOf(instanceOf(UnknownHostException.class),
            hasProperty("message", containsString(HTTP_PROXY.getHost()))));

    makeRequest(httpClient, "http://somehost");
}

From source file:org.springframework.cloud.config.server.environment.ConfigurableHttpConnectionFactoryIntegrationTests.java

@Test
public void httpProxy_notCalled() throws Exception {
    String repoUrl = "https://myrepo/repo.git";
    new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE)
            .properties(gitProperties(repoUrl, HTTP_PROXY, null)).run();
    HttpClient httpClient = getHttpClientForUrl(repoUrl);
    this.expectedException.expectCause(
            allOf(instanceOf(UnknownHostException.class), hasProperty("message", containsString("somehost"))));

    makeRequest(httpClient, "https://somehost");
}

From source file:org.springframework.cloud.config.server.environment.ConfigurableHttpConnectionFactoryIntegrationTests.java

@Test
public void httpProxy_fromSystemProperty() throws Exception {
    ProxySelector defaultProxySelector = ProxySelector.getDefault();
    try {//from   w w w.  ja v a  2s.c om
        ProxySelector.setDefault(new ProxySelector() {
            @Override
            public List<Proxy> select(URI uri) {
                InetSocketAddress address = new InetSocketAddress(HTTP_PROXY.getHost(), HTTP_PROXY.getPort());
                Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
                return Collections.singletonList(proxy);
            }

            @Override
            public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {

            }
        });
        String repoUrl = "https://myrepo/repo.git";
        new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE)
                .properties(new String[] { "spring.cloud.config.server.git.uri=" + repoUrl }).run();
        HttpClient httpClient = getHttpClientForUrl(repoUrl);
        this.expectedException.expectCause(allOf(instanceOf(UnknownHostException.class),
                hasProperty("message", containsString(HTTP_PROXY.getHost()))));

        makeRequest(httpClient, "http://somehost");
    } finally {
        ProxySelector.setDefault(defaultProxySelector);
    }
}

From source file:com.fitbur.testify.junit.system.SpringBootSystemTest.java

@Override
protected Statement methodBlock(FrameworkMethod method) {
    TestClass testClass = getTestClass();
    Class<?> javaClass = testClass.getJavaClass();

    Object testInstance;//from  w  ww  .j ava  2  s . c  o  m

    try {
        testInstance = createTest();
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    TestContext testContext = getTestContext(javaClass);
    testContext.setTestInstance(testInstance);

    Optional<App> appOptional = testContext.getAnnotation(App.class);
    checkState(appOptional.isPresent(), "Test class '%s' is not annotated with @App annotation.",
            testClass.getName());

    App app = appOptional.get();
    Set<Class<?>> modules = testContext.getAnnotations(Module.class).parallelStream().map(p -> p.value())
            .collect(toSet());

    Set<Object> sources = new LinkedHashSet<>();
    sources.add(app.value());
    sources.addAll(modules);

    application = new SpringApplicationBuilder(sources.toArray()).bannerMode(Banner.Mode.OFF).build();

    APPLICATION_TEST_CONTEXTS.computeIfAbsent(application, p -> testContext);

    application.run();

    SpringBootDescriptor descriptor = APPLICATION_DESCRIPTORS.get(application);

    ServiceLocator serviceLocator = descriptor.getServiceLocator();
    serviceLocator.addConstant(descriptor.getClass().getSimpleName(), descriptor);

    try {
        URI baseURI = new URI("http", null, "0.0.0.0", descriptor.getServletContainer().getPort(),
                descriptor.getServletContext().getContextPath(), null, null);

        SpringBootClientDescriptor clientDescriptor = new SpringBootClientDescriptor(app, testContext, baseURI);
        ServiceLoader<ClientProvider> clientProviderLoader = ServiceLoader.load(ClientProvider.class);
        ArrayList<ClientProvider> clientProviders = Lists.newArrayList(clientProviderLoader);

        checkState(!clientProviders.isEmpty(), "ClientInstance provider not found in the classpath");
        checkState(clientProviders.size() == 1, "Multiple ClientInstance provider found in the classpath. "
                + "Please insure there is only one ClientInstance provider in the classpath.");

        ClientProvider clientProvider = clientProviders.get(0);
        Object context = clientProvider.configuration(clientDescriptor);

        testContext.getConfigMethod(context.getClass()).map(m -> m.getMethod()).ifPresent(m -> {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                try {
                    m.setAccessible(true);
                    m.invoke(testInstance, context);
                } catch (Exception e) {
                    checkState(false, "Call to config method '%s' in test class '%s' failed due to: ",
                            m.getName(), clientDescriptor.getTestClassName(), e.getMessage());
                }

                return null;
            });
        });

        serverInstance = new SpringBootServerInstance(descriptor.getServletContainer(), baseURI);
        serviceLocator.addConstant(serverInstance.getClass().getSimpleName(), serverInstance);

        clientInstance = clientProvider.init(clientDescriptor, context);
        serviceLocator.addConstant(clientInstance.getClass().getSimpleName(), clientInstance);

        TestCaseInstance testCaseInstance = new TestCaseInstance(method.getName(), testInstance);
        serviceLocator.addConstant(testCaseInstance.getTestName(), testCaseInstance);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    SystemTestReifier reifier = new SystemTestReifier(testContext, serviceLocator, testInstance);
    SystemTestCreator creator = new SystemTestCreator(testContext, reifier, serviceLocator);

    if (testContext.getCutDescriptor() != null) {
        creator.cut();
    }

    Set<FieldDescriptor> real = testContext.getFieldDescriptors().values().parallelStream()
            .filter(p -> !p.getInstance().isPresent())
            .filter(p -> p.hasAnnotations(descriptor.getServiceAnnotations().getInjectors())).collect(toSet());

    creator.real(real);

    SystemTestVerifier verifier = new SystemTestVerifier(testContext, LOGGER);
    verifier.wiring();

    Statement statement = methodInvoker(method, testInstance);
    statement = possiblyExpectingExceptions(method, testInstance, statement);
    statement = withBefores(method, testInstance, statement);
    statement = withAfters(method, testInstance, statement);
    statement = withRules(method, testInstance, statement);

    return statement;
}

From source file:org.springframework.cloud.config.server.environment.JGitEnvironmentRepositoryConcurrencyTests.java

@Test
public void vanilla() throws Exception {
    String uri = ConfigServerTestUtils.prepareLocalRepo();
    this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE)
            .properties("spring.cloud.config.server.git.uri:" + uri).run();
    final EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class);
    ExecutorService threads = Executors.newFixedThreadPool(4);
    List<Future<Boolean>> tasks = new ArrayList<Future<Boolean>>();
    for (int i = 0; i < 30; i++) {
        tasks.add(threads.submit(new Runnable() {
            @Override// w w  w. j a  v a2  s  .  c  o m
            public void run() {
                repository.findOne("bar", "staging", "master");
            }
        }, true));
    }
    for (Future<Boolean> future : tasks) {
        future.get();
    }
    Environment environment = repository.findOne("bar", "staging", "master");
    assertThat(environment.getPropertySources().size()).isEqualTo(2);
    assertThat(environment.getName()).isEqualTo("bar");
    assertThat(environment.getProfiles()).isEqualTo(new String[] { "staging" });
    assertThat(environment.getLabel()).isEqualTo("master");
}

From source file:org.springframework.cloud.config.server.environment.NativeEnvironmentRepository.java

@Override
public Environment findOne(String config, String profile, String label) {
    SpringApplicationBuilder builder = new SpringApplicationBuilder(PropertyPlaceholderAutoConfiguration.class);
    ConfigurableEnvironment environment = getEnvironment(profile);
    builder.environment(environment);// w  ww .  j  a  va  2  s.  c o m
    builder.web(false).bannerMode(Mode.OFF);
    if (!logger.isDebugEnabled()) {
        // Make the mini-application startup less verbose
        builder.logStartupInfo(false);
    }
    String[] args = getArgs(config, profile, label);
    // Explicitly set the listeners (to exclude logging listener which would change
    // log levels in the caller)
    builder.application().setListeners(Arrays.asList(new ConfigFileApplicationListener()));
    ConfigurableApplicationContext context = builder.run(args);
    environment.getPropertySources().remove("profiles");
    try {
        return clean(new PassthruEnvironmentRepository(environment).findOne(config, profile, label));
    } finally {
        context.close();
    }
}

From source file:org.springframework.cloud.config.server.NativeEnvironmentRepository.java

@Override
public Environment findOne(String config, String profile, String label) {
    SpringApplicationBuilder builder = new SpringApplicationBuilder(PropertyPlaceholderAutoConfiguration.class);
    ConfigurableEnvironment environment = getEnvironment(profile);
    builder.environment(environment);//from  ww  w  .  j  av  a  2  s. c o  m
    builder.web(false).showBanner(false);
    String[] args = getArgs(config, label);
    // Explicitly set the listeners (to exclude logging listener which would change
    // log levels in the caller)
    builder.application().setListeners(Collections.singletonList(new ConfigFileApplicationListener()));
    ConfigurableApplicationContext context = builder.run(args);
    environment.getPropertySources().remove("profiles");
    try {
        return clean(new PassthruEnvironmentRepository(environment).findOne(config, profile, label));
    } finally {
        context.close();
    }
}

From source file:org.springframework.cloud.dataflow.server.local.metrics.FakeMetricsCollector.java

public static void main(String[] args) {
    int port = SocketUtils.findAvailableTcpPort();
    LOGGER.info("Setting Fake Metrics Collector port to " + port);
    new SpringApplicationBuilder(FakeMetricsCollector.class).properties("fakeMetricsCollector.port:" + port)
            .properties("logging.level.org.springframework.boot=debug").build()
            .run("--spring.config.location=classpath:/org/springframework/cloud/dataflow/server/local/metrics/fakeMetricsCollectorConfig.yml");
}