org.springframework.boot.builder.SpringApplicationBuilder Java Examples

The following examples show how to use org.springframework.boot.builder.SpringApplicationBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HealthIndicatorsConfigurationTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
public static ConfigurableApplicationContext createBinderTestContext(
		String[] additionalClasspathDirectories, String... properties)
		throws IOException {
	URL[] urls = ObjectUtils.isEmpty(additionalClasspathDirectories) ? new URL[0]
			: new URL[additionalClasspathDirectories.length];
	if (!ObjectUtils.isEmpty(additionalClasspathDirectories)) {
		for (int i = 0; i < additionalClasspathDirectories.length; i++) {
			urls[i] = new URL(new ClassPathResource(additionalClasspathDirectories[i])
					.getURL().toString() + "/");
		}
	}
	ClassLoader classLoader = new URLClassLoader(urls,
			BinderFactoryAutoConfigurationTests.class.getClassLoader());

	return new SpringApplicationBuilder(SimpleSource.class)
			.resourceLoader(new DefaultResourceLoader(classLoader))
			.properties(properties).web(WebApplicationType.NONE).run();
}
 
Example #2
Source File: SpringFunctionInitializer.java    From service-block-samples with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected void initialize() {
	if (!this.initialized.compareAndSet(false, true)) {
		return;
	}
	logger.info("Initializing: " + configurationClass);
	SpringApplicationBuilder builder = new SpringApplicationBuilder(
			configurationClass);
	ConfigurableApplicationContext context = builder.web(false).run();
	context.getAutowireCapableBeanFactory().autowireBean(this);
	String name = context.getEnvironment().getProperty("function.name");
	boolean defaultName = false;
	if (name == null) {
		name = "function";
		defaultName = true;
	}
	if (this.catalog == null) {
		this.function = context.getBean(name, Function.class);
	}
	else {
		this.function = this.catalog.lookupFunction(name);
		this.name = name;
		if (this.function == null) {
			if (defaultName) {
				name = "consumer";
			}
			this.consumer = this.catalog.lookupConsumer(name);
			this.name = name;
			if (this.consumer == null) {
				if (defaultName) {
					name = "supplier";
				}
				this.supplier = this.catalog.lookupSupplier(name);
				this.name = name;
			}
		}
	}
	this.context = context;
}
 
Example #3
Source File: ErrorBindingTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
public void testConfigurationWithCustomErrorHandler() {
	ApplicationContext context = new SpringApplicationBuilder(
			TestChannelBinderConfiguration.getCompleteConfiguration(
					ErrorBindingTests.ErrorConfigurationWithCustomErrorHandler.class))
							.web(WebApplicationType.NONE)
							.run("--spring.cloud.stream.bindings.input.consumer.max-attempts=1",
									"--spring.jmx.enabled=false");

	InputDestination source = context.getBean(InputDestination.class);
	source.send(new GenericMessage<byte[]>("Hello".getBytes()));
	source.send(new GenericMessage<byte[]>("Hello".getBytes()));
	source.send(new GenericMessage<byte[]>("Hello".getBytes()));

	ErrorConfigurationWithCustomErrorHandler errorConfiguration = context
			.getBean(ErrorConfigurationWithCustomErrorHandler.class);
	assertThat(errorConfiguration.counter == 6);
}
 
Example #4
Source File: EncryptionBootstrapConfigurationTests.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void nonExistentKeystoreLocationShouldNotBeAllowed() {
	try {
		new SpringApplicationBuilder(EncryptionBootstrapConfiguration.class)
				.web(WebApplicationType.NONE)
				.properties("encrypt.key-store.location:classpath:/server.jks1",
						"encrypt.key-store.password:letmein",
						"encrypt.key-store.alias:mytestkey",
						"encrypt.key-store.secret:changeme")
				.run();
		then(false).as(
				"Should not create an application context with invalid keystore location")
				.isTrue();
	}
	catch (Exception e) {
		then(e).hasRootCauseInstanceOf(IllegalStateException.class);
	}
}
 
Example #5
Source File: InstancesControllerIntegrationTest.java    From Moss with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    instance = new SpringApplicationBuilder().sources(AdminReactiveApplicationTest.TestAdminApplication.class)
                                             .web(WebApplicationType.REACTIVE)
                                             .run("--server.port=0", "--eureka.client.enabled=false");

    localPort = instance.getEnvironment().getProperty("local.server.port", Integer.class, 0);

    this.client = WebTestClient.bindToServer().baseUrl("http://localhost:" + localPort).build();
    this.register_as_test = "{ \"name\": \"test\", \"healthUrl\": \"http://localhost:" +
                            localPort +
                            "/application/health\" }";
    this.register_as_twice = "{ \"name\": \"twice\", \"healthUrl\": \"http://localhost:" +
                             localPort +
                             "/application/health\" }";
}
 
Example #6
Source File: ContentTypeTckTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
public void typelessToPojoWithTextHeaderContentTypeBinding() {
	ApplicationContext context = new SpringApplicationBuilder(
			TypelessToPojoStreamListener.class).web(WebApplicationType.NONE)
					.run("--spring.jmx.enabled=false");
	InputDestination source = context.getBean(InputDestination.class);
	OutputDestination target = context.getBean(OutputDestination.class);
	String jsonPayload = "{\"name\":\"oleg\"}";
	source.send(MessageBuilder.withPayload(jsonPayload.getBytes())
			.setHeader(MessageHeaders.CONTENT_TYPE, MimeType.valueOf("text/plain"))
			.build());
	Message<byte[]> outputMessage = target.receive();
	assertThat(outputMessage.getHeaders().get(MessageHeaders.CONTENT_TYPE))
			.isEqualTo(MimeTypeUtils.APPLICATION_JSON);
	assertThat(new String(outputMessage.getPayload(), StandardCharsets.UTF_8))
			.isEqualTo(jsonPayload);
}
 
Example #7
Source File: JGitEnvironmentRepositoryIntegrationTests.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
@Test
public void singleElementArrayIndexSearchPath() throws IOException {
	String uri = ConfigServerTestUtils.prepareLocalRepo("nested-repo");
	this.context = new SpringApplicationBuilder(TestConfiguration.class)
			.web(WebApplicationType.NONE)
			.run("--spring.cloud.config.server.git.uri=" + uri,
					"--spring.cloud.config.server.git.searchPaths[0]={application}");
	JGitEnvironmentRepository repository = this.context
			.getBean(JGitEnvironmentRepository.class);
	assertThat(repository.getSearchPaths()).containsExactly("{application}");
	assertThat(
			Arrays.equals(repository.getSearchPaths(),
					new JGitEnvironmentRepository(repository.getEnvironment(),
							new JGitEnvironmentProperties()).getSearchPaths()))
									.isFalse();
}
 
Example #8
Source File: MultipleInputOutputFunctionTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
public void testSingleInputMultiOutput() {
	try (ConfigurableApplicationContext context = new SpringApplicationBuilder(
			TestChannelBinderConfiguration.getCompleteConfiguration(
					ReactiveFunctionConfiguration.class))
							.web(WebApplicationType.NONE)
							.run("--spring.jmx.enabled=false",
								"--spring.cloud.function.definition=singleInputMultipleOutputs")) {
		context.getBean(InputDestination.class);

		InputDestination inputDestination = context.getBean(InputDestination.class);
		OutputDestination outputDestination = context.getBean(OutputDestination.class);

		for (int i = 0; i < 10; i++) {
			inputDestination.send(MessageBuilder.withPayload(String.valueOf(i).getBytes()).build(), "singleInputMultipleOutputs-in-0");
		}

		int counter = 0;
		for (int i = 0; i < 5; i++) {
			Message<byte[]> even = outputDestination.receive(0, "singleInputMultipleOutputs-out-0");
			assertThat(even.getPayload()).isEqualTo(("EVEN: " + String.valueOf(counter++)).getBytes());
			Message<byte[]> odd = outputDestination.receive(0, "singleInputMultipleOutputs-out-1");
			assertThat(odd.getPayload()).isEqualTo(("ODD: " + String.valueOf(counter++)).getBytes());
		}
	}
}
 
Example #9
Source File: InitializerApplication.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

		SpringApplication springApplication =
			new SpringApplicationBuilder(InitializerApplication.class).build();

		assertThat(springApplication).isNotNull();
		assertThat(springApplication.getWebApplicationType()).isEqualTo(WebApplicationType.NONE);

		ConfigurableApplicationContext applicationContext = springApplication.run(args);

		assertThat(applicationContext).isNotNull();
		assertThat(applicationContext).isNotInstanceOf(WebApplicationContext.class);
		assertThat(springApplication.getWebApplicationType()).isNotEqualTo(WebApplicationType.SERVLET);
	}
 
Example #10
Source File: ApplicationWebXml.java    From cubeai with Apache License 2.0 5 votes vote down vote up
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    /**
     * set a default to use when no profile is configured.
     */
    DefaultProfileUtil.addDefaultProfile(application.application());
    return application.sources(UaaApp.class);
}
 
Example #11
Source File: ContentTypeTckTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Test
public void _jsonToPojoWrongDefaultContentTypeProperty() {
	ApplicationContext context = new SpringApplicationBuilder(
			PojoToPojoStreamListener.class).web(WebApplicationType.NONE).run(
					"--spring.cloud.stream.default.contentType=text/plain",
					"--spring.jmx.enabled=false");
	InputDestination source = context.getBean(InputDestination.class);
	TestChannelBinder binder = context.getBean(TestChannelBinder.class);
	String jsonPayload = "{\"name\":\"oleg\"}";
	source.send(new GenericMessage<>(jsonPayload.getBytes()));
	assertThat(binder.getLastError().getPayload() instanceof MessagingException)
			.isTrue();
}
 
Example #12
Source File: ContentTypeTckTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Test
public void withInternalPipeline() {
	ApplicationContext context = new SpringApplicationBuilder(InternalPipeLine.class)
			.web(WebApplicationType.NONE).run("--spring.jmx.enabled=false");
	InputDestination source = context.getBean(InputDestination.class);
	OutputDestination target = context.getBean(OutputDestination.class);
	String jsonPayload = "{\"name\":\"oleg\"}";
	source.send(new GenericMessage<>(jsonPayload.getBytes()));
	Message<byte[]> outputMessage = target.receive();
	assertThat(new String(outputMessage.getPayload())).isEqualTo("OLEG");
}
 
Example #13
Source File: ApplicationWebXml.java    From klask-io with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    /*
      set a default to use when no profile is configured.
     */
    DefaultProfileUtil.addDefaultProfile(application.application());
    return application.sources(KlaskApp.class);
}
 
Example #14
Source File: ApplicationWebXml.java    From e-commerce-microservice with Apache License 2.0 5 votes vote down vote up
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    /**
     * set a default to use when no profile is configured.
     */
    DefaultProfileUtil.addDefaultProfile(application.application());
    return application.sources(InvoiceApp.class);
}
 
Example #15
Source File: ContentTypeTckTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void _toStringDefaultContentTypePropertyUnknownContentType() {
	ApplicationContext context = new SpringApplicationBuilder(
			StringToStringStreamListener.class).web(WebApplicationType.NONE).run(
					"--spring.cloud.stream.default.contentType=foo/bar",
					"--spring.jmx.enabled=false");
	InputDestination source = context.getBean(InputDestination.class);
	TestChannelBinder binder = context.getBean(TestChannelBinder.class);
	String jsonPayload = "{\"name\":\"oleg\"}";
	source.send(new GenericMessage<>(jsonPayload.getBytes()));
	assertThat(
			binder.getLastError().getPayload() instanceof MessageConversionException)
					.isTrue();
}
 
Example #16
Source File: ApplicationWebXml.java    From OpenIoE with Apache License 2.0 5 votes vote down vote up
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    /**
     * set a default to use when no profile is configured.
     */
    DefaultProfileUtil.addDefaultProfile(application.application());
    return application.sources(IoeApp.class);
}
 
Example #17
Source File: KubernetesDiscoveryClientAutoConfigurationPropertiesTests.java    From spring-cloud-kubernetes with Apache License 2.0 5 votes vote down vote up
private void setup(String... env) {
	this.context = new SpringApplicationBuilder(
			PropertyPlaceholderAutoConfiguration.class,
			KubernetesClientTestConfiguration.class,
			KubernetesDiscoveryClientAutoConfiguration.class)
					.web(org.springframework.boot.WebApplicationType.NONE)
					.properties(env).run();
}
 
Example #18
Source File: Application.java    From fiware-cepheus with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {

        new SpringApplicationBuilder()
                .sources(Application.class)
                .showBanner(false)
                .run(args);
    }
 
Example #19
Source File: GeodeLoggingApplicationListenerUnitTests.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
@Test
public void supportSourceTypeReturnsFalse() {

	assertThat(this.listener.supportsSourceType(null)).isFalse();
	assertThat(this.listener.supportsSourceType(Object.class)).isFalse();
	assertThat(this.listener.supportsSourceType(BeanFactory.class)).isFalse();
	assertThat(this.listener.supportsSourceType(SpringApplicationBuilder.class)).isFalse();
}
 
Example #20
Source File: DeviceHiveAuthApplication.java    From devicehive-java-server with Apache License 2.0 5 votes vote down vote up
public static void main(String... args) {
    ConfigurableApplicationContext context = new SpringApplicationBuilder()
            .sources(DeviceHiveAuthApplication.class)
            .web(true)
            .run(args);

    context.registerShutdownHook();
}
 
Example #21
Source File: DeviceHiveFrontendApplication.java    From devicehive-java-server with Apache License 2.0 5 votes vote down vote up
public static void main(String... args) {
    ConfigurableApplicationContext context = new SpringApplicationBuilder()
            .sources(DeviceHiveFrontendApplication.class)
            .web(true)
            .run(args);

    context.registerShutdownHook();
}
 
Example #22
Source File: BatchExecutionEventTests.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
private void testListener(String channelBinding, CountDownLatch latch, Class<?> clazz)
		throws Exception {
	this.applicationContext = new SpringApplicationBuilder()
			.sources(this.getConfigurations(clazz, JobConfiguration.class)).build()
			.run(getCommandLineParams(channelBinding));

	assertThat(latch.await(1, TimeUnit.SECONDS)).isTrue();
}
 
Example #23
Source File: AdminServerApplication.java    From oneplatform with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	long starTime = System.currentTimeMillis();
	new SpringApplicationBuilder(AdminServerApplication.class).web(true).run(args);
	long endTime = System.currentTimeMillis();
	long time = endTime - starTime;
	System.out.println("\nStart Time: " + time / 1000 + " s");
	System.out.println("...............................................................");
	System.out.println(".........AdminServerApplication starts successfully...........");
	System.out.println("...............................................................");

}
 
Example #24
Source File: BindingHandlerAdviseTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidatedValueValue() {
	ValidatedProps validatedProps = new SpringApplicationBuilder(SampleConfiguration.class)
			.web(WebApplicationType.NONE).run("--props.value=2", "--spring.jmx.enabled=false")
			.getBean(ValidatedProps.class);
	assertThat(validatedProps.getValue()).isEqualTo(2);
}
 
Example #25
Source File: SpringEventListenerBootstrap.java    From thinking-in-spring-boot-samples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    new SpringApplicationBuilder(Object.class) // 非 @Configuration 充当配置源
            .listeners(event ->                // 添加 ApplicationListener
                    System.out.printf("监听到事件: %s , 事件源 : %s\n"
                            , event.getClass().getSimpleName(), event.getSource())
            )
            .web(false)                        // 非 Web 应用
            .run(args)                         // 运行 SpringApplication
            .close();                          // 关闭 ConfigurableApplicationContext
}
 
Example #26
Source File: EdgeApplication.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
  new SpringApplicationBuilder().sources(EdgeApplication.class).web(WebApplicationType.NONE).build().run(args);

  SelfServiceInvoker invoker = BeanUtils.getBean("SelfServiceInvoker");
  invoker.latch.await(10, TimeUnit.SECONDS);
  TestMgr.check(invoker.result, "hello");

  TestMgr.summary();
  if (!TestMgr.errors().isEmpty()) {
    System.exit(1);
  }
}
 
Example #27
Source File: AdminUiReactiveApplicationTest.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setUp() {
	this.instance = new SpringApplicationBuilder().sources(TestAdminApplication.class)
			.web(WebApplicationType.REACTIVE).run("--server.port=0",
					"--spring.boot.admin.ui.extension-resource-locations=classpath:/META-INF/test-extensions/",
					"--spring.boot.admin.ui.available-languages=de");

	super.setUp(this.instance.getEnvironment().getProperty("local.server.port", Integer.class, 0));
}
 
Example #28
Source File: CalendarApplication.java    From Spring-Security-Third-Edition with MIT License 4 votes vote down vote up
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(CalendarApplication.class);
}
 
Example #29
Source File: Application.java    From spring-security-firebase with MIT License 4 votes vote down vote up
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
	return application.sources(Application.class);
}
 
Example #30
Source File: CosonleApplication.java    From springboot-plus with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(CosonleApplication.class);
}