Merge branch '1.5.x'

pull/7854/head
Phillip Webb 8 years ago
commit b1cb8bb3d9

@ -90,7 +90,7 @@ public class EndpointMBeanExportAutoConfiguration {
@Bean @Bean
@ConditionalOnBean(AuditEventRepository.class) @ConditionalOnBean(AuditEventRepository.class)
@ConditionalOnEnabledEndpoint("auditevents") @ConditionalOnEnabledEndpoint("auditevents")
public AuditEventsJmxEndpoint abstractEndpointMBean( public AuditEventsJmxEndpoint auditEventsEndpoint(
AuditEventRepository auditEventRepository) { AuditEventRepository auditEventRepository) {
return new AuditEventsJmxEndpoint(this.objectMapper, auditEventRepository); return new AuditEventsJmxEndpoint(this.objectMapper, auditEventRepository);
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2015 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -19,6 +19,7 @@ package org.springframework.boot.actuate.autoconfigure;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.context.annotation.DeferredImportSelector; import org.springframework.context.annotation.DeferredImportSelector;
@ -27,6 +28,7 @@ import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.core.io.support.SpringFactoriesLoader; import org.springframework.core.io.support.SpringFactoriesLoader;
import org.springframework.core.type.AnnotationMetadata; import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;
/** /**
* Selects configuration classes for the management context configuration. Entries are * Selects configuration classes for the management context configuration. Entries are
@ -47,11 +49,26 @@ class ManagementContextConfigurationsImportSelector
@Override @Override
public String[] selectImports(AnnotationMetadata metadata) { public String[] selectImports(AnnotationMetadata metadata) {
// Find all possible auto configuration classes, filtering duplicates // Find all possible auto configuration classes, filtering duplicates
List<String> factories = new ArrayList<String>( List<String> names = loadFactoryNames();
new LinkedHashSet<String>(SpringFactoriesLoader.loadFactoryNames( Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
ManagementContextConfiguration.class, this.classLoader))); for (String factoryName : names) {
AnnotationAwareOrderComparator.sort(factories); classes.add(ClassUtils.resolveClassName(factoryName, this.classLoader));
return factories.toArray(new String[0]); }
return getSortedClassNames(new ArrayList<Class<?>>(classes));
}
protected List<String> loadFactoryNames() {
return SpringFactoriesLoader
.loadFactoryNames(ManagementContextConfiguration.class, this.classLoader);
}
private String[] getSortedClassNames(List<Class<?>> classes) {
AnnotationAwareOrderComparator.sort(classes);
List<String> names = new ArrayList<String>();
for (Class<?> sourceClass : classes) {
names.add(sourceClass.getName());
}
return names.toArray(new String[names.size()]);
} }
@Override @Override

@ -22,7 +22,6 @@ import org.springframework.boot.actuate.endpoint.Endpoint;
import org.springframework.boot.actuate.endpoint.EndpointProperties; import org.springframework.boot.actuate.endpoint.EndpointProperties;
import org.springframework.context.EnvironmentAware; import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
/** /**
@ -33,7 +32,6 @@ import org.springframework.util.ObjectUtils;
* @author Phillip Webb * @author Phillip Webb
* @since 1.5.0 * @since 1.5.0
*/ */
@ManagedResource
public abstract class AbstractJmxEndpoint implements JmxEndpoint, EnvironmentAware { public abstract class AbstractJmxEndpoint implements JmxEndpoint, EnvironmentAware {
private final DataConverter dataConverter; private final DataConverter dataConverter;

@ -28,6 +28,7 @@ import org.springframework.boot.actuate.audit.AuditEventRepository;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.jmx.export.annotation.ManagedOperation; import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/** /**
* {@link JmxEndpoint} for {@link AuditEventRepository}. * {@link JmxEndpoint} for {@link AuditEventRepository}.
@ -72,8 +73,11 @@ public class AuditEventsJmxEndpoint extends AbstractJmxEndpoint {
private Date parseDate(String date) { private Date parseDate(String date) {
try { try {
if (StringUtils.hasLength(date)) {
return new SimpleDateFormat(DATE_FORMAT).parse(date); return new SimpleDateFormat(DATE_FORMAT).parse(date);
} }
return null;
}
catch (ParseException ex) { catch (ParseException ex) {
throw new IllegalArgumentException(ex); throw new IllegalArgumentException(ex);
} }

@ -20,7 +20,6 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.actuate.endpoint.Endpoint; import org.springframework.boot.actuate.endpoint.Endpoint;
import org.springframework.jmx.export.annotation.ManagedAttribute; import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.jmx.export.annotation.ManagedResource;
/** /**
* Simple wrapper around {@link Endpoint} implementations that provide actuator data of * Simple wrapper around {@link Endpoint} implementations that provide actuator data of
@ -29,7 +28,6 @@ import org.springframework.jmx.export.annotation.ManagedResource;
* @author Christian Dupuis * @author Christian Dupuis
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
@ManagedResource
public class DataEndpointMBean extends EndpointMBean { public class DataEndpointMBean extends EndpointMBean {
/** /**

@ -20,7 +20,6 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.actuate.endpoint.Endpoint; import org.springframework.boot.actuate.endpoint.Endpoint;
import org.springframework.jmx.export.annotation.ManagedAttribute; import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.ClassUtils; import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
@ -35,7 +34,6 @@ import org.springframework.util.ObjectUtils;
* @see JmxEndpoint * @see JmxEndpoint
* @see DataEndpointMBean * @see DataEndpointMBean
*/ */
@ManagedResource
public abstract class EndpointMBean implements JmxEndpoint { public abstract class EndpointMBean implements JmxEndpoint {
private final DataConverter dataConverter; private final DataConverter dataConverter;

@ -46,9 +46,12 @@ import org.springframework.jmx.export.MBeanExporter;
import org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource; import org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource;
import org.springframework.jmx.export.annotation.ManagedResource; import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler; import org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler;
import org.springframework.jmx.export.metadata.InvalidMetadataException;
import org.springframework.jmx.export.metadata.JmxAttributeSource;
import org.springframework.jmx.export.naming.MetadataNamingStrategy; import org.springframework.jmx.export.naming.MetadataNamingStrategy;
import org.springframework.jmx.export.naming.SelfNaming; import org.springframework.jmx.export.naming.SelfNaming;
import org.springframework.jmx.support.ObjectNameManager; import org.springframework.jmx.support.ObjectNameManager;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
/** /**
@ -70,7 +73,7 @@ public class EndpointMBeanExporter extends MBeanExporter
private static final Log logger = LogFactory.getLog(EndpointMBeanExporter.class); private static final Log logger = LogFactory.getLog(EndpointMBeanExporter.class);
private final AnnotationJmxAttributeSource attributeSource = new AnnotationJmxAttributeSource(); private final AnnotationJmxAttributeSource attributeSource = new EndpointJmxAttributeSource();
private final MetadataMBeanInfoAssembler assembler = new MetadataMBeanInfoAssembler( private final MetadataMBeanInfoAssembler assembler = new MetadataMBeanInfoAssembler(
this.attributeSource); this.attributeSource);
@ -253,8 +256,8 @@ public class EndpointMBeanExporter extends MBeanExporter
if (bean instanceof SelfNaming) { if (bean instanceof SelfNaming) {
return ((SelfNaming) bean).getObjectName(); return ((SelfNaming) bean).getObjectName();
} }
if (bean instanceof EndpointMBean) { if (bean instanceof JmxEndpoint) {
return getObjectName((EndpointMBean) bean, beanKey); return getObjectName((JmxEndpoint) bean, beanKey);
} }
return this.defaultNamingStrategy.getObjectName(bean, beanKey); return this.defaultNamingStrategy.getObjectName(bean, beanKey);
} }
@ -363,4 +366,19 @@ public class EndpointMBeanExporter extends MBeanExporter
} }
} }
/**
* {@link JmxAttributeSource} for {@link JmxEndpoint JmxEndpoints}.
*/
private static class EndpointJmxAttributeSource extends AnnotationJmxAttributeSource {
@Override
public org.springframework.jmx.export.metadata.ManagedResource getManagedResource(
Class<?> beanClass) throws InvalidMetadataException {
Assert.state(super.getManagedResource(beanClass) == null,
"@ManagedResource annotation found on JmxEndpoint " + beanClass);
return new org.springframework.jmx.export.metadata.ManagedResource();
}
}
} }

@ -17,11 +17,13 @@
package org.springframework.boot.actuate.endpoint.jmx; package org.springframework.boot.actuate.endpoint.jmx;
import org.springframework.boot.actuate.endpoint.Endpoint; import org.springframework.boot.actuate.endpoint.Endpoint;
import org.springframework.jmx.export.annotation.ManagedResource;
/** /**
* A strategy for the JMX layer on top of an {@link Endpoint}. Implementations are allowed * A strategy for the JMX layer on top of an {@link Endpoint}. Implementations are allowed
* to use {@code @ManagedAttribute} and the full Spring JMX machinery. Implementations may * to use {@code @ManagedAttribute} and the full Spring JMX machinery but should not use
* be backed by an actual {@link Endpoint} or may be specifically designed for JMX only. * the {@link ManagedResource @ManagedResource} annotation. Implementations may be backed
* by an actual {@link Endpoint} or may be specifically designed for JMX only.
* *
* @author Phillip Webb * @author Phillip Webb
* @since 1.5.0 * @since 1.5.0

@ -24,7 +24,6 @@ import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoint;
import org.springframework.boot.logging.LogLevel; import org.springframework.boot.logging.LogLevel;
import org.springframework.jmx.export.annotation.ManagedAttribute; import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.jmx.export.annotation.ManagedOperation; import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.util.Assert; import org.springframework.util.Assert;
/** /**
@ -33,7 +32,6 @@ import org.springframework.util.Assert;
* @author Vedran Pavic * @author Vedran Pavic
* @since 1.5.0 * @since 1.5.0
*/ */
@ManagedResource
public class LoggersEndpointMBean extends EndpointMBean { public class LoggersEndpointMBean extends EndpointMBean {
public LoggersEndpointMBean(String beanName, Endpoint<?> endpoint, public LoggersEndpointMBean(String beanName, Endpoint<?> endpoint,

@ -21,7 +21,6 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.actuate.endpoint.Endpoint; import org.springframework.boot.actuate.endpoint.Endpoint;
import org.springframework.boot.actuate.endpoint.ShutdownEndpoint; import org.springframework.boot.actuate.endpoint.ShutdownEndpoint;
import org.springframework.jmx.export.annotation.ManagedOperation; import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedResource;
/** /**
* Special endpoint wrapper for {@link ShutdownEndpoint}. * Special endpoint wrapper for {@link ShutdownEndpoint}.
@ -29,7 +28,6 @@ import org.springframework.jmx.export.annotation.ManagedResource;
* @author Christian Dupuis * @author Christian Dupuis
* @author Andy Wilkinson * @author Andy Wilkinson
*/ */
@ManagedResource
public class ShutdownEndpointMBean extends EndpointMBean { public class ShutdownEndpointMBean extends EndpointMBean {
/** /**

@ -0,0 +1,68 @@
/*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.actuate.autoconfigure;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.springframework.core.annotation.Order;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link ManagementContextConfigurationsImportSelector}.
*
* @author Phillip Webb
*/
public class ManagementContextConfigurationsImportSelectorTests {
@Test
public void selectImportsShouldOrderResult() throws Exception {
String[] imports = new TestManagementContextConfigurationsImportSelector()
.selectImports(null);
assertThat(imports).containsExactly(A.class.getName(), B.class.getName(),
C.class.getName());
}
private static class TestManagementContextConfigurationsImportSelector
extends ManagementContextConfigurationsImportSelector {
@Override
protected List<String> loadFactoryNames() {
return Arrays.asList(C.class.getName(), A.class.getName(), B.class.getName());
}
}
@Order(1)
private static class A {
}
@Order(2)
private static class B {
}
@Order(3)
private static class C {
}
}

@ -0,0 +1,85 @@
/*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.orm.jpa;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.jdbc.DatabaseDriver;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.jdbc.support.MetaDataAccessException;
import org.springframework.orm.jpa.vendor.Database;
/**
* Utility to lookup well known {@link Database Databases} from a {@link DataSource}.
*
* @author Eddú Meléndez
* @author Phillip Webb
*/
final class DatabaseLookup {
private static final Log logger = LogFactory.getLog(DatabaseLookup.class);
private static final Map<DatabaseDriver, Database> LOOKUP;
static {
Map<DatabaseDriver, Database> map = new HashMap<DatabaseDriver, Database>();
map.put(DatabaseDriver.DERBY, Database.DERBY);
map.put(DatabaseDriver.H2, Database.H2);
map.put(DatabaseDriver.HSQLDB, Database.HSQL);
map.put(DatabaseDriver.MYSQL, Database.MYSQL);
map.put(DatabaseDriver.ORACLE, Database.ORACLE);
map.put(DatabaseDriver.POSTGRESQL, Database.POSTGRESQL);
map.put(DatabaseDriver.SQLSERVER, Database.SQL_SERVER);
map.put(DatabaseDriver.DB2, Database.DB2);
map.put(DatabaseDriver.INFORMIX, Database.INFORMIX);
LOOKUP = Collections.unmodifiableMap(map);
}
private DatabaseLookup() {
}
/**
* Return the most suitable {@link Database} for the given {@link DataSource}.
* @param dataSource the source {@link DataSource}
* @return the most sutable {@link Database}
*/
public static Database getDatabase(DataSource dataSource) {
if (dataSource == null) {
return Database.DEFAULT;
}
try {
String url = (String) JdbcUtils.extractDatabaseMetaData(dataSource, "getURL");
DatabaseDriver driver = DatabaseDriver.fromJdbcUrl(url);
Database database = LOOKUP.get(driver);
if (database != null) {
return database;
}
}
catch (MetaDataAccessException ex) {
logger.warn("Unable to determine jdbc url from datasource", ex);
}
return Database.DEFAULT;
}
}

@ -1,73 +0,0 @@
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.orm.jpa;
import org.springframework.boot.jdbc.DatabaseDriver;
import org.springframework.orm.jpa.vendor.Database;
/**
* Mapper between {@link Database} and {@link DatabaseDriver}.
*
* @author Eddú Meléndez
*/
enum DatabasePlatform {
DB2(Database.DB2, DatabaseDriver.DB2),
DERBY(Database.DERBY, DatabaseDriver.DERBY),
H2(Database.H2, DatabaseDriver.H2),
HSQL(Database.HSQL, DatabaseDriver.HSQLDB),
INFORMIX(Database.INFORMIX, DatabaseDriver.INFORMIX),
MYSQL(Database.MYSQL, DatabaseDriver.MYSQL),
ORACLE(Database.ORACLE, DatabaseDriver.ORACLE),
POSTGRESQL(Database.POSTGRESQL, DatabaseDriver.POSTGRESQL),
SQL_SERVER(Database.SQL_SERVER, DatabaseDriver.SQLSERVER);
private final Database database;
private final DatabaseDriver driver;
DatabasePlatform(Database database, DatabaseDriver driver) {
this.database = database;
this.driver = driver;
}
public Database getDatabase() {
return this.database;
}
public DatabaseDriver getDriver() {
return this.driver;
}
public static DatabasePlatform fromDatabaseDriver(DatabaseDriver driver) {
for (DatabasePlatform mapper : values()) {
if (mapper.getDriver() == driver) {
return mapper;
}
}
return null;
}
}

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2016 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -21,15 +21,9 @@ import java.util.Map;
import javax.sql.DataSource; import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.autoconfigure.jdbc.EmbeddedDatabaseConnection; import org.springframework.boot.autoconfigure.jdbc.EmbeddedDatabaseConnection;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty; import org.springframework.boot.context.properties.NestedConfigurationProperty;
import org.springframework.boot.jdbc.DatabaseDriver;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.jdbc.support.MetaDataAccessException;
import org.springframework.orm.jpa.vendor.Database; import org.springframework.orm.jpa.vendor.Database;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@ -45,8 +39,6 @@ import org.springframework.util.StringUtils;
@ConfigurationProperties(prefix = "spring.jpa") @ConfigurationProperties(prefix = "spring.jpa")
public class JpaProperties { public class JpaProperties {
private static final Log logger = LogFactory.getLog(JpaProperties.class);
/** /**
* Additional native properties to set on the JPA provider. * Additional native properties to set on the JPA provider.
*/ */
@ -144,19 +136,7 @@ public class JpaProperties {
if (this.database != null) { if (this.database != null) {
return this.database; return this.database;
} }
try { return DatabaseLookup.getDatabase(dataSource);
String jdbcUrl = (String) JdbcUtils.extractDatabaseMetaData(dataSource,
"getURL");
DatabasePlatform databasePlatform = DatabasePlatform.fromDatabaseDriver(
DatabaseDriver.fromJdbcUrl(jdbcUrl));
if (databasePlatform != null) {
return databasePlatform.getDatabase();
}
}
catch (MetaDataAccessException ex) {
logger.warn("Unable to determine jdbc url from datasource", ex);
}
return Database.DEFAULT;
} }
public static class Hibernate { public static class Hibernate {

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2016 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -41,7 +41,7 @@ import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.mock; import static org.mockito.Mockito.mock;
/** /**
* Tests for {@link HibernateJpaAutoConfiguration}. * Tests for {@link HibernateJpaAutoConfiguration}.
@ -120,7 +120,8 @@ public class CustomHibernateJpaAutoConfigurationTests {
PropertyPlaceholderAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class,
HibernateJpaAutoConfiguration.class); HibernateJpaAutoConfiguration.class);
this.context.refresh(); this.context.refresh();
HibernateJpaVendorAdapter bean = this.context.getBean(HibernateJpaVendorAdapter.class); HibernateJpaVendorAdapter bean = this.context
.getBean(HibernateJpaVendorAdapter.class);
Database database = (Database) ReflectionTestUtils.getField(bean, "database"); Database database = (Database) ReflectionTestUtils.getField(bean, "database");
assertThat(database).isEqualTo(Database.H2); assertThat(database).isEqualTo(Database.H2);
} }
@ -139,8 +140,8 @@ public class CustomHibernateJpaAutoConfigurationTests {
DataSource dataSource = mock(DataSource.class); DataSource dataSource = mock(DataSource.class);
try { try {
given(dataSource.getConnection()).willReturn(mock(Connection.class)); given(dataSource.getConnection()).willReturn(mock(Connection.class));
given(dataSource.getConnection().getMetaData()).willReturn( given(dataSource.getConnection().getMetaData())
mock(DatabaseMetaData.class)); .willReturn(mock(DatabaseMetaData.class));
} }
catch (SQLException e) { catch (SQLException e) {
// Do nothing // Do nothing

@ -0,0 +1,106 @@
/*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.orm.jpa;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import javax.sql.DataSource;
import org.junit.Test;
import org.springframework.orm.jpa.vendor.Database;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link DatabaseLookup}.
*
* @author Eddú Meléndez
* @author Phillip Webb
*/
public class DatabaseLookupTests {
@Test
public void getDatabaseWhenDataSourceIsNullShouldReturnDefault() throws Exception {
assertThat(DatabaseLookup.getDatabase(null)).isEqualTo(Database.DEFAULT);
}
@Test
public void getDatabaseWhenDataSourceIsUnknownShouldReturnDefault() throws Exception {
testGetDatabase("jdbc:idontexist:", Database.DEFAULT);
}
@Test
public void getDatabaseWhenDerbyShouldReturnDerby() throws Exception {
testGetDatabase("jdbc:derby:", Database.DERBY);
}
@Test
public void getDatabaseWhenH2ShouldReturnH2() throws Exception {
testGetDatabase("jdbc:h2:", Database.H2);
}
@Test
public void getDatabaseWhenHsqldbShouldReturnHsqldb() throws Exception {
testGetDatabase("jdbc:hsqldb:", Database.HSQL);
}
@Test
public void getDatabaseWhenMysqlShouldReturnMysql() throws Exception {
testGetDatabase("jdbc:mysql:", Database.MYSQL);
}
@Test
public void getDatabaseWhenOracleShouldReturnOracle() throws Exception {
testGetDatabase("jdbc:oracle:", Database.ORACLE);
}
@Test
public void getDatabaseWhenPostgresShouldReturnPostgres() throws Exception {
testGetDatabase("jdbc:postgresql:", Database.POSTGRESQL);
}
@Test
public void getDatabaseWhenSqlserverShouldReturnSqlserver() throws Exception {
testGetDatabase("jdbc:sqlserver:", Database.SQL_SERVER);
}
@Test
public void getDatabaseWhenDb2ShouldReturnDb2() throws Exception {
testGetDatabase("jdbc:db2:", Database.DB2);
}
@Test
public void getDatabaseWhenInformixShouldReturnInformix() throws Exception {
testGetDatabase("jdbc:informix-sqli:", Database.INFORMIX);
}
private void testGetDatabase(String url, Database expected) throws Exception {
DataSource dataSource = mock(DataSource.class);
Connection connection = mock(Connection.class);
DatabaseMetaData metaData = mock(DatabaseMetaData.class);
given(dataSource.getConnection()).willReturn(connection);
given(connection.getMetaData()).willReturn(metaData);
given(metaData.getURL()).willReturn(url);
Database database = DatabaseLookup.getDatabase(dataSource);
assertThat(database).isEqualTo(expected);
}
}

@ -1,86 +0,0 @@
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.orm.jpa;
import org.junit.Test;
import org.springframework.boot.jdbc.DatabaseDriver;
import org.springframework.orm.jpa.vendor.Database;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link DatabasePlatform}.
*
* @author Eddú Meléndez
*/
public class DatabasePlatformTests {
@Test
public void databaseDriverLookups() {
assertThat(DatabasePlatform.fromDatabaseDriver(DatabaseDriver.DB2))
.isEqualTo(DatabasePlatform.DB2);
assertThat(DatabasePlatform.fromDatabaseDriver(DatabaseDriver.DERBY))
.isEqualTo(DatabasePlatform.DERBY);
assertThat(DatabasePlatform.fromDatabaseDriver(DatabaseDriver.H2))
.isEqualTo(DatabasePlatform.H2);
assertThat(DatabasePlatform.fromDatabaseDriver(DatabaseDriver.HSQLDB))
.isEqualTo(DatabasePlatform.HSQL);
assertThat(DatabasePlatform.fromDatabaseDriver(DatabaseDriver.INFORMIX))
.isEqualTo(DatabasePlatform.INFORMIX);
assertThat(DatabasePlatform.fromDatabaseDriver(DatabaseDriver.MYSQL))
.isEqualTo(DatabasePlatform.MYSQL);
assertThat(DatabasePlatform.fromDatabaseDriver(DatabaseDriver.ORACLE))
.isEqualTo(DatabasePlatform.ORACLE);
assertThat(DatabasePlatform.fromDatabaseDriver(DatabaseDriver.POSTGRESQL))
.isEqualTo(DatabasePlatform.POSTGRESQL);
assertThat(DatabasePlatform.fromDatabaseDriver(DatabaseDriver.SQLSERVER))
.isEqualTo(DatabasePlatform.SQL_SERVER);
}
@Test
public void databaseLookups() {
assertThat(DatabasePlatform.fromDatabaseDriver(DatabaseDriver.DB2)
.getDatabase())
.isEqualTo(Database.DB2);
assertThat(DatabasePlatform.fromDatabaseDriver(DatabaseDriver.DERBY)
.getDatabase())
.isEqualTo(Database.DERBY);
assertThat(DatabasePlatform.fromDatabaseDriver(DatabaseDriver.H2)
.getDatabase())
.isEqualTo(Database.H2);
assertThat(DatabasePlatform.fromDatabaseDriver(DatabaseDriver.HSQLDB)
.getDatabase())
.isEqualTo(Database.HSQL);
assertThat(DatabasePlatform.fromDatabaseDriver(DatabaseDriver.INFORMIX)
.getDatabase())
.isEqualTo(Database.INFORMIX);
assertThat(DatabasePlatform.fromDatabaseDriver(DatabaseDriver.MYSQL)
.getDatabase())
.isEqualTo(Database.MYSQL);
assertThat(DatabasePlatform.fromDatabaseDriver(DatabaseDriver.ORACLE)
.getDatabase())
.isEqualTo(Database.ORACLE);
assertThat(DatabasePlatform.fromDatabaseDriver(DatabaseDriver.POSTGRESQL)
.getDatabase())
.isEqualTo(Database.POSTGRESQL);
assertThat(DatabasePlatform.fromDatabaseDriver(DatabaseDriver.SQLSERVER)
.getDatabase())
.isEqualTo(Database.SQL_SERVER);
}
}

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2016 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -48,7 +48,6 @@ import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse; import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.InterceptingClientHttpRequestFactory;
import org.springframework.http.client.support.BasicAuthorizationInterceptor; import org.springframework.http.client.support.BasicAuthorizationInterceptor;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.ClassUtils; import org.springframework.util.ClassUtils;
@ -144,11 +143,19 @@ public class TestRestTemplate {
if (username == null) { if (username == null) {
return; return;
} }
List<ClientHttpRequestInterceptor> interceptors = Collections List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
.<ClientHttpRequestInterceptor>singletonList( if (interceptors == null) {
new BasicAuthorizationInterceptor(username, password)); interceptors = Collections.emptyList();
restTemplate.setRequestFactory(new InterceptingClientHttpRequestFactory( }
restTemplate.getRequestFactory(), interceptors)); interceptors = new ArrayList<ClientHttpRequestInterceptor>(interceptors);
Iterator<ClientHttpRequestInterceptor> iterator = interceptors.iterator();
while (iterator.hasNext()) {
if (iterator.next() instanceof BasicAuthorizationInterceptor) {
iterator.remove();
}
}
interceptors.add(new BasicAuthorizationInterceptor(username, password));
restTemplate.setInterceptors(interceptors);
} }
/** /**
@ -985,8 +992,7 @@ public class TestRestTemplate {
public TestRestTemplate withBasicAuth(String username, String password) { public TestRestTemplate withBasicAuth(String username, String password) {
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
restTemplate.setMessageConverters(getRestTemplate().getMessageConverters()); restTemplate.setMessageConverters(getRestTemplate().getMessageConverters());
restTemplate.setInterceptors( restTemplate.setInterceptors(getRestTemplate().getInterceptors());
removeBasicAuthInterceptorIfPresent(getRestTemplate().getInterceptors()));
restTemplate.setRequestFactory(getRestTemplate().getRequestFactory()); restTemplate.setRequestFactory(getRestTemplate().getRequestFactory());
restTemplate.setUriTemplateHandler(getRestTemplate().getUriTemplateHandler()); restTemplate.setUriTemplateHandler(getRestTemplate().getUriTemplateHandler());
TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplate, username, TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplate, username,
@ -996,19 +1002,6 @@ public class TestRestTemplate {
return testRestTemplate; return testRestTemplate;
} }
private List<ClientHttpRequestInterceptor> removeBasicAuthInterceptorIfPresent(
List<ClientHttpRequestInterceptor> interceptors) {
List<ClientHttpRequestInterceptor> updatedInterceptors = new ArrayList<ClientHttpRequestInterceptor>(
interceptors);
Iterator<ClientHttpRequestInterceptor> iterator = updatedInterceptors.iterator();
while (iterator.hasNext()) {
if (iterator.next() instanceof BasicAuthorizationInterceptor) {
iterator.remove();
}
}
return interceptors;
}
/** /**
* Options used to customize the Apache Http Client if it is used. * Options used to customize the Apache Http Client if it is used.
*/ */

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2016 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -160,16 +160,15 @@ public class TestRestTemplateTests {
.isInstanceOf(CustomHttpComponentsClientHttpRequestFactory.class); .isInstanceOf(CustomHttpComponentsClientHttpRequestFactory.class);
assertThat(basicAuthTemplate.getRestTemplate().getUriTemplateHandler()) assertThat(basicAuthTemplate.getRestTemplate().getUriTemplateHandler())
.isSameAs(originalTemplate.getRestTemplate().getUriTemplateHandler()); .isSameAs(originalTemplate.getRestTemplate().getUriTemplateHandler());
assertThat(basicAuthTemplate.getRestTemplate().getInterceptors()) assertThat(basicAuthTemplate.getRestTemplate().getInterceptors()).hasSize(1);
.containsExactlyElementsOf(
originalTemplate.getRestTemplate().getInterceptors());
assertBasicAuthorizationInterceptorCredentials(basicAuthTemplate, "user", assertBasicAuthorizationInterceptorCredentials(basicAuthTemplate, "user",
"password"); "password");
} }
@Test @Test
public void withBasicAuthReplacesBasicAuthInterceptorWhenAlreadyPresent() { public void withBasicAuthReplacesBasicAuthInterceptorWhenAlreadyPresent() {
TestRestTemplate original = new TestRestTemplate("foo", "bar"); TestRestTemplate original = new TestRestTemplate("foo", "bar")
.withBasicAuth("replace", "repalce");
TestRestTemplate basicAuth = original.withBasicAuth("user", "password"); TestRestTemplate basicAuth = original.withBasicAuth("user", "password");
assertThat(basicAuth.getRestTemplate().getMessageConverters()) assertThat(basicAuth.getRestTemplate().getMessageConverters())
.containsExactlyElementsOf( .containsExactlyElementsOf(
@ -181,8 +180,7 @@ public class TestRestTemplateTests {
.isInstanceOf(CustomHttpComponentsClientHttpRequestFactory.class); .isInstanceOf(CustomHttpComponentsClientHttpRequestFactory.class);
assertThat(basicAuth.getRestTemplate().getUriTemplateHandler()) assertThat(basicAuth.getRestTemplate().getUriTemplateHandler())
.isSameAs(original.getRestTemplate().getUriTemplateHandler()); .isSameAs(original.getRestTemplate().getUriTemplateHandler());
assertThat(basicAuth.getRestTemplate().getInterceptors()) assertThat(basicAuth.getRestTemplate().getInterceptors()).hasSize(1);
.containsExactlyElementsOf(original.getRestTemplate().getInterceptors());
assertBasicAuthorizationInterceptorCredentials(basicAuth, "user", "password"); assertBasicAuthorizationInterceptorCredentials(basicAuth, "user", "password");
} }

@ -1,5 +1,5 @@
/* /*
* Copyright 2012-2016 the original author or authors. * Copyright 2012-2017 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -72,8 +72,8 @@ public enum DatabaseDriver {
/** /**
* Maria DB. * Maria DB.
*/ */
MARIADB("MySQL", "org.mariadb.jdbc.Driver", MARIADB("MySQL", "org.mariadb.jdbc.Driver", "org.mariadb.jdbc.MariaDbDataSource",
"org.mariadb.jdbc.MariaDbDataSource", "SELECT 1") { "SELECT 1") {
@Override @Override
public String getId() { public String getId() {
@ -181,6 +181,7 @@ public enum DatabaseDriver {
protected Collection<String> getUrlPrefixes() { protected Collection<String> getUrlPrefixes() {
return Arrays.asList("informix-sqli", "informix-direct"); return Arrays.asList("informix-sqli", "informix-direct");
} }
}; };
private final String productName; private final String productName;

Loading…
Cancel
Save