Merge branch 'JAVA-1164' into JAVA-1192

This commit is contained in:
amit.pandey 2020-04-12 00:05:00 +05:30
commit d76fdbbe14
20 changed files with 310 additions and 8 deletions

View File

@ -1,6 +1,7 @@
package com.baeldung.jackson.date;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
@ -8,6 +9,8 @@ import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.TimeZone;
@ -30,7 +33,7 @@ import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
public class JacksonDateUnitTest {
@Test
public void whenSerializingDateWithJackson_thenSerializedToNumber() throws JsonProcessingException, ParseException {
public void whenSerializingDateWithJackson_thenSerializedToTimestamp() throws JsonProcessingException, ParseException {
final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
@ -61,6 +64,21 @@ public class JacksonDateUnitTest {
final String result = mapper.writeValueAsString(event);
assertThat(result, containsString("1970-01-01T02:30:00.000+00:00"));
}
@Test
public void whenDeserialisingZonedDateTimeWithDefaults_thenNotCorrect()
throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.findAndRegisterModules();
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("UTC"));
String converted = objectMapper.writeValueAsString(now);
ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
System.out.println("serialized: " + now);
System.out.println("restored: " + restored);
assertThat(now, is(restored));
}
@Test
public void whenSettingObjectMapperDateFormat_thenCorrect() throws JsonProcessingException, ParseException {

View File

@ -0,0 +1,21 @@
package com.baeldung.hibernate.audit;
import java.util.Optional;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
@Component("auditorProvider")
public class AuditorAwareImpl implements AuditorAware<String> {
@Override
public String getCurrentAuditor() {
return Optional.ofNullable(SecurityContextHolder.getContext())
.map(e -> e.getAuthentication())
.map(Authentication::getName)
.orElse(null);
}
}

View File

@ -46,7 +46,7 @@ import com.google.common.base.Preconditions;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = { "com.baeldung.persistence" }, transactionManagerRef = "jpaTransactionManager")
@EnableJpaAuditing
@EnableJpaAuditing(auditorAwareRef = "auditorProvider")
@PropertySource({ "classpath:persistence-h2.properties" })
@ComponentScan({ "com.baeldung.persistence" })
public class PersistenceConfig {

View File

@ -24,6 +24,22 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<exclusions>
<exclusion>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<!--Test -->
<dependency>
@ -32,4 +48,5 @@
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,16 @@
package com.baeldung.annotations;
import java.util.Properties;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ConditionalBeanConfiguration {
@Conditional(HibernateCondition.class)
Properties additionalProperties() {
// application specific properties
return new Properties();
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.annotations;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HealthCheckController {
private static final String STATUS = "UP";
@GetMapping("/health")
public ResponseEntity<String> healthCheck() {
return ResponseEntity.ok(STATUS);
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.annotations;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
public class HibernateCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
// application specific condition check
return true;
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.annotations;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnResource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
@Configuration
@ConditionalOnClass(DataSource.class)
public class MySQLAutoconfiguration {
@Bean
@ConditionalOnBean(name = "dataSource")
LocalContainerEntityManagerFactoryBean entityManagerFactory() throws IOException {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" });
final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
@ConditionalOnProperty(name = "usemysql", havingValue = "local")
DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.hsqldb.jdbcDriver");
dataSource.setUrl("jdbc:hsqldb:mem:testdb");
dataSource.setUsername( "sa" );
dataSource.setPassword( "" );
return dataSource;
}
@ConditionalOnResource(resources = "classpath:mysql.properties")
Properties additionalProperties() throws IOException {
final Properties additionalProperties = new Properties();
try (InputStream inputStream = new ClassPathResource("classpath:mysql.properties").getInputStream()) {
additionalProperties.load(inputStream);
}
return additionalProperties;
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.annotations;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Configuration;
@Configuration
public class WebApplicationSpecificConfiguration {
@ConditionalOnWebApplication
HealthCheckController healthCheckController() {
return new HealthCheckController();
}
}

View File

@ -7,7 +7,7 @@ import org.springframework.context.annotation.ComponentScan;
import com.baeldung.configurationproperties.ConfigProperties;
@SpringBootApplication
@ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class })
@ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class, Database.class })
public class ConfigPropertiesDemoApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(ConfigPropertiesDemoApplication.class).initializers(new JsonPropertyContextInitializer())

View File

@ -0,0 +1,33 @@
package com.baeldung.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "database")
public class Database {
private String url;
private String username;
private String password;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

View File

@ -1,4 +1,8 @@
management.endpoints.web.exposure.include=refresh
spring.properties.refreshDelay=1000
spring.config.location=file:extra.properties
spring.main.allow-bean-definition-overriding=true
spring.main.allow-bean-definition-overriding=true
database.url=jdbc:postgresql:/localhost:5432/instance
database.username=foo
database.password=bar

View File

@ -0,0 +1,30 @@
package com.baeldung.configurationproperties;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.properties.ConfigPropertiesDemoApplication;
import com.baeldung.properties.Database;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConfigPropertiesDemoApplication.class)
@TestPropertySource("classpath:application.properties")
public class DatabasePropertiesIntegrationTest {
@Autowired
private Database database;
@Test
public void testDatabaseProperties() {
Assert.assertNotNull(database);
Assert.assertEquals("jdbc:postgresql:/localhost:5432/instance", database.getUrl());
Assert.assertEquals("foo", database.getUsername());
Assert.assertEquals("bar", database.getPassword());
}
}

View File

@ -1,4 +1,8 @@
management.endpoints.web.exposure.include=refresh
spring.properties.refreshDelay=1000
spring.config.location=file:extra.properties
spring.main.allow-bean-definition-overriding=true
spring.main.allow-bean-definition-overriding=true
database.url=jdbc:postgresql:/localhost:5432/instance
database.username=foo
database.password=bar

View File

@ -0,0 +1,32 @@
package com.baeldung.spring.web.config;
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class MainWebAppInitializer implements WebApplicationInitializer {
private String TMP_FOLDER = "/tmp";
private int MAX_UPLOAD_SIZE = 5 * 1024 * 1024;
@Override
public void onStartup(ServletContext sc) throws ServletException {
ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(
new GenericWebApplicationContext()));
appServlet.setLoadOnStartup(1);
MultipartConfigElement multipartConfigElement = new MultipartConfigElement(TMP_FOLDER,
MAX_UPLOAD_SIZE, MAX_UPLOAD_SIZE * 2, MAX_UPLOAD_SIZE / 2);
appServlet.setMultipartConfig(multipartConfigElement);
}
}

View File

@ -12,6 +12,7 @@ import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.http.MediaType;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
@ -121,4 +122,11 @@ public class WebConfig implements WebMvcConfigurer {
public ExcelPOIHelper excelPOIHelper() {
return new ExcelPOIHelper();
}
@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(100000);
return multipartResolver;
}
}

View File

@ -72,7 +72,7 @@ public class FooMappingExamplesController {
@RequestMapping(value = "/foos", produces = { "application/json", "application/xml" })
@ResponseBody
public String getFoosAsJsonFromREST() {
public String getFoosAsJsonFromBrowser() {
return "Get some Foos with Header New";
}

View File

@ -12,7 +12,7 @@ import java.sql.SQLException;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
public class SpringRetryIntegrationTest {
public class SpringRetryTest {
@Autowired
private MyService myService;

View File

@ -0,0 +1,16 @@
package com.baeldung.session.web.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.springframework.web.WebApplicationInitializer;
public class MainWebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext sc) throws ServletException {
sc.getSessionCookieConfig().setHttpOnly(true);
sc.getSessionCookieConfig().setSecure(true);
}
}

View File

@ -18,7 +18,7 @@ public class SecurityController {
@RequestMapping(value = "/username2", method = RequestMethod.GET)
@ResponseBody
public String currentUserNameSimple(final Principal principal) {
public String currentUserName(final Principal principal) {
return principal.getName();
}