minor formatting cleanup
This commit is contained in:
+1
-1
@@ -16,7 +16,7 @@ import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
* <code>@ServletComponentScan(basePackageClasses = {AttrListener.class, HelloFilter.class, HelloServlet.class, EchoServlet.class})</code>
|
||||
* </li></ul>
|
||||
*/
|
||||
@SpringBootApplication(exclude=MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
@ServletComponentScan("com.baeldung.annotation.servletcomponentscan.components")
|
||||
public class SpringBootAnnotatedApp {
|
||||
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude=MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
@ComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.components")
|
||||
public class SpringBootPlainApp {
|
||||
|
||||
|
||||
+2
-3
@@ -9,9 +9,8 @@ public class AttrListener implements ServletContextListener {
|
||||
|
||||
@Override
|
||||
public void contextInitialized(ServletContextEvent servletContextEvent) {
|
||||
servletContextEvent
|
||||
.getServletContext()
|
||||
.setAttribute("servlet-context-attr", "test");
|
||||
servletContextEvent.getServletContext()
|
||||
.setAttribute("servlet-context-attr", "test");
|
||||
System.out.println("context init");
|
||||
}
|
||||
|
||||
|
||||
+2
-3
@@ -16,9 +16,8 @@ public class EchoServlet extends HttpServlet {
|
||||
@Override
|
||||
public void doPost(HttpServletRequest request, HttpServletResponse response) {
|
||||
try {
|
||||
Path path = File
|
||||
.createTempFile("echo", "tmp")
|
||||
.toPath();
|
||||
Path path = File.createTempFile("echo", "tmp")
|
||||
.toPath();
|
||||
Files.copy(request.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
|
||||
Files.copy(path, response.getOutputStream());
|
||||
Files.delete(path);
|
||||
|
||||
+2
-3
@@ -18,9 +18,8 @@ public class HelloFilter implements Filter {
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
|
||||
servletResponse
|
||||
.getOutputStream()
|
||||
.print(filterConfig.getInitParameter("msg"));
|
||||
servletResponse.getOutputStream()
|
||||
.print(filterConfig.getInitParameter("msg"));
|
||||
filterChain.doFilter(servletRequest, servletResponse);
|
||||
}
|
||||
|
||||
|
||||
+5
-5
@@ -8,22 +8,22 @@ import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
@WebServlet(urlPatterns = "/hello", initParams = { @WebInitParam(name = "msg", value = "hello")})
|
||||
@WebServlet(urlPatterns = "/hello", initParams = { @WebInitParam(name = "msg", value = "hello") })
|
||||
public class HelloServlet extends HttpServlet {
|
||||
|
||||
private ServletConfig servletConfig;
|
||||
|
||||
@Override
|
||||
public void init(ServletConfig servletConfig){
|
||||
public void init(ServletConfig servletConfig) {
|
||||
this.servletConfig = servletConfig;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doGet(HttpServletRequest request, HttpServletResponse response) {
|
||||
try {
|
||||
response
|
||||
.getOutputStream()
|
||||
.write(servletConfig.getInitParameter("msg").getBytes());
|
||||
response.getOutputStream()
|
||||
.write(servletConfig.getInitParameter("msg")
|
||||
.getBytes());
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
+7
-9
@@ -92,21 +92,19 @@ public class MySQLAutoconfiguration {
|
||||
|
||||
static class HibernateCondition extends SpringBootCondition {
|
||||
|
||||
private static final String[] CLASS_NAMES = {
|
||||
"org.hibernate.ejb.HibernateEntityManager",
|
||||
"org.hibernate.jpa.HibernateEntityManager" };
|
||||
private static final String[] CLASS_NAMES = { "org.hibernate.ejb.HibernateEntityManager", "org.hibernate.jpa.HibernateEntityManager" };
|
||||
|
||||
@Override
|
||||
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
|
||||
ConditionMessage.Builder message = ConditionMessage.forCondition("Hibernate");
|
||||
|
||||
return Arrays.stream(CLASS_NAMES)
|
||||
.filter(className -> ClassUtils.isPresent(className, context.getClassLoader()))
|
||||
.map(className -> ConditionOutcome
|
||||
.match(message.found("class").items(Style.NORMAL, className)))
|
||||
.findAny()
|
||||
.orElseGet(() -> ConditionOutcome
|
||||
.noMatch(message.didNotFind("class", "classes").items(Style.NORMAL, Arrays.asList(CLASS_NAMES))));
|
||||
.filter(className -> ClassUtils.isPresent(className, context.getClassLoader()))
|
||||
.map(className -> ConditionOutcome.match(message.found("class")
|
||||
.items(Style.NORMAL, className)))
|
||||
.findAny()
|
||||
.orElseGet(() -> ConditionOutcome.noMatch(message.didNotFind("class", "classes")
|
||||
.items(Style.NORMAL, Arrays.asList(CLASS_NAMES))));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+2
-2
@@ -2,6 +2,6 @@ package com.baeldung.autoconfiguration.example;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface MyUserRepository extends JpaRepository<MyUser, String>{
|
||||
|
||||
public interface MyUserRepository extends JpaRepository<MyUser, String> {
|
||||
|
||||
}
|
||||
|
||||
@@ -10,13 +10,13 @@ public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
applicationContext = SpringApplication.run(Application.class, args);
|
||||
|
||||
|
||||
displayAllBeans();
|
||||
}
|
||||
|
||||
|
||||
public static void displayAllBeans() {
|
||||
String[] allBeanNames = applicationContext.getBeanDefinitionNames();
|
||||
for(String beanName : allBeanNames) {
|
||||
for (String beanName : allBeanNames) {
|
||||
System.out.println(beanName);
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -12,9 +12,9 @@ import com.baeldung.displayallbeans.service.FooService;
|
||||
public class FooController {
|
||||
@Autowired
|
||||
private FooService fooService;
|
||||
|
||||
@RequestMapping(value="/displayallbeans")
|
||||
public String getHeaderAndBody (Map<String, Object> model){
|
||||
|
||||
@RequestMapping(value = "/displayallbeans")
|
||||
public String getHeaderAndBody(Map<String, Object> model) {
|
||||
model.put("header", fooService.getHeader());
|
||||
model.put("message", fooService.getBody());
|
||||
return "displayallbeans";
|
||||
|
||||
@@ -4,15 +4,13 @@ import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class FooService {
|
||||
|
||||
|
||||
public String getHeader() {
|
||||
return "Display All Beans";
|
||||
}
|
||||
|
||||
|
||||
public String getBody() {
|
||||
return "This is a sample application that displays all beans "
|
||||
+ "in Spring IoC container using ListableBeanFactory interface "
|
||||
+ "and Spring Boot Actuators.";
|
||||
return "This is a sample application that displays all beans " + "in Spring IoC container using ListableBeanFactory interface " + "and Spring Boot Actuators.";
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
+4
-1
@@ -18,7 +18,10 @@ public class PersistenceConfig {
|
||||
@Bean
|
||||
public DataSource dataSource() {
|
||||
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
|
||||
EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.H2).addScript("schema-expressions.sql").addScript("data-expressions.sql").build();
|
||||
EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.H2)
|
||||
.addScript("schema-expressions.sql")
|
||||
.addScript("data-expressions.sql")
|
||||
.build();
|
||||
return db;
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude=MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
public class FailureAnalyzerApplication {
|
||||
@RolesAllowed("*")
|
||||
public static void main(String[] args) {
|
||||
|
||||
+7
-9
@@ -4,8 +4,7 @@ import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
|
||||
import org.springframework.boot.diagnostics.AbstractFailureAnalyzer;
|
||||
import org.springframework.boot.diagnostics.FailureAnalysis;
|
||||
|
||||
public class MyBeanNotOfRequiredTypeFailureAnalyzer
|
||||
extends AbstractFailureAnalyzer<BeanNotOfRequiredTypeException> {
|
||||
public class MyBeanNotOfRequiredTypeFailureAnalyzer extends AbstractFailureAnalyzer<BeanNotOfRequiredTypeException> {
|
||||
|
||||
@Override
|
||||
protected FailureAnalysis analyze(Throwable rootFailure, BeanNotOfRequiredTypeException cause) {
|
||||
@@ -13,16 +12,15 @@ public class MyBeanNotOfRequiredTypeFailureAnalyzer
|
||||
}
|
||||
|
||||
private String getDescription(BeanNotOfRequiredTypeException ex) {
|
||||
return String.format("The bean %s could not be injected as %s because it is of type %s",
|
||||
ex.getBeanName(),
|
||||
ex.getRequiredType().getName(),
|
||||
ex.getActualType().getName());
|
||||
return String.format("The bean %s could not be injected as %s because it is of type %s", ex.getBeanName(), ex.getRequiredType()
|
||||
.getName(),
|
||||
ex.getActualType()
|
||||
.getName());
|
||||
}
|
||||
|
||||
private String getAction(BeanNotOfRequiredTypeException ex) {
|
||||
return String.format("Consider creating a bean with name %s of type %s",
|
||||
ex.getBeanName(),
|
||||
ex.getRequiredType().getName());
|
||||
return String.format("Consider creating a bean with name %s of type %s", ex.getBeanName(), ex.getRequiredType()
|
||||
.getName());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import org.springframework.core.io.ClassPathResource;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(scanBasePackages = { "com.baeldung.git" }, exclude=MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication(scanBasePackages = { "com.baeldung.git" }, exclude = MySQLAutoconfiguration.class)
|
||||
public class CommitIdApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(CommitIdApplication.class, args);
|
||||
|
||||
@@ -23,7 +23,7 @@ public class GraphqlConfiguration {
|
||||
}
|
||||
return new PostDao(posts);
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
public AuthorDao authorDao() {
|
||||
List<Author> authors = new ArrayList<>();
|
||||
@@ -36,12 +36,12 @@ public class GraphqlConfiguration {
|
||||
}
|
||||
return new AuthorDao(authors);
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
public PostResolver postResolver(AuthorDao authorDao) {
|
||||
return new PostResolver(authorDao);
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
public AuthorResolver authorResolver(PostDao postDao) {
|
||||
return new AuthorResolver(postDao);
|
||||
|
||||
@@ -13,7 +13,8 @@ public class Mutation implements GraphQLMutationResolver {
|
||||
|
||||
public Post writePost(String title, String text, String category, String author) {
|
||||
Post post = new Post();
|
||||
post.setId(UUID.randomUUID().toString());
|
||||
post.setId(UUID.randomUUID()
|
||||
.toString());
|
||||
post.setTitle(title);
|
||||
post.setText(text);
|
||||
post.setCategory(category);
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude=MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
public class InternationalizationApp {
|
||||
@RolesAllowed("*")
|
||||
public static void main(String[] args) {
|
||||
|
||||
@@ -5,11 +5,9 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude=MySQLAutoconfiguration.class)
|
||||
public class App
|
||||
{
|
||||
public static void main( String[] args )
|
||||
{
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
public class App {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(App.class, args);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,12 +7,12 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
public class HomeController {
|
||||
|
||||
@RequestMapping("/")
|
||||
public String root(){
|
||||
public String root() {
|
||||
return "Index Page";
|
||||
}
|
||||
|
||||
|
||||
@RequestMapping("/local")
|
||||
public String local(){
|
||||
public String local() {
|
||||
return "/local";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import org.springframework.boot.web.support.SpringBootServletInitializer;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude=MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
public class ApplicationMain extends SpringBootServletInitializer {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
@@ -26,10 +26,13 @@ public class WebMvcConfigure extends WebMvcConfigurerAdapter {
|
||||
configurer.enable();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver());
|
||||
registry.addResourceHandler("/resources/**")
|
||||
.addResourceLocations("/resources/")
|
||||
.setCachePeriod(3600)
|
||||
.resourceChain(true)
|
||||
.addResolver(new PathResourceResolver());
|
||||
}
|
||||
|
||||
@Bean
|
||||
|
||||
@@ -10,7 +10,8 @@ import org.springframework.core.env.ConfigurableEnvironment;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan(basePackages = { "com.baeldung.servlets.*" })
|
||||
@PropertySource("classpath:custom.properties") public class PropertySourcesLoader {
|
||||
@PropertySource("classpath:custom.properties")
|
||||
public class PropertySourcesLoader {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(PropertySourcesLoader.class);
|
||||
|
||||
|
||||
+3
-4
@@ -7,14 +7,13 @@ import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
@WebServlet(name = "AnnotationServlet",
|
||||
description = "Example Servlet Using Annotations",
|
||||
urlPatterns = { "/annotationservlet" })
|
||||
@WebServlet(name = "AnnotationServlet", description = "Example Servlet Using Annotations", urlPatterns = { "/annotationservlet" })
|
||||
public class AnnotationServlet extends HttpServlet {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
request.getRequestDispatcher("/annotationservlet.jsp").forward(request, response);
|
||||
request.getRequestDispatcher("/annotationservlet.jsp")
|
||||
.forward(request, response);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,6 @@ package com.baeldung.toggle;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
public interface EmployeeRepository extends CrudRepository<Employee, Long>{
|
||||
public interface EmployeeRepository extends CrudRepository<Employee, Long> {
|
||||
|
||||
}
|
||||
|
||||
@@ -10,13 +10,15 @@ import org.togglz.core.context.FeatureContext;
|
||||
|
||||
public enum MyFeatures implements Feature {
|
||||
|
||||
@Label("Employee Management Feature") @EnabledByDefault @DefaultActivationStrategy(id = SystemPropertyActivationStrategy.ID,
|
||||
parameters = { @ActivationParameter(name = SystemPropertyActivationStrategy.PARAM_PROPERTY_NAME, value = "employee.feature"),
|
||||
@ActivationParameter(name = SystemPropertyActivationStrategy.PARAM_PROPERTY_VALUE, value = "true") })
|
||||
@Label("Employee Management Feature")
|
||||
@EnabledByDefault
|
||||
@DefaultActivationStrategy(id = SystemPropertyActivationStrategy.ID, parameters = { @ActivationParameter(name = SystemPropertyActivationStrategy.PARAM_PROPERTY_NAME, value = "employee.feature"),
|
||||
@ActivationParameter(name = SystemPropertyActivationStrategy.PARAM_PROPERTY_VALUE, value = "true") })
|
||||
EMPLOYEE_MANAGEMENT_FEATURE;
|
||||
|
||||
public boolean isActive() {
|
||||
return FeatureContext.getFeatureManager().isActive(this);
|
||||
return FeatureContext.getFeatureManager()
|
||||
.isActive(this);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -8,13 +8,13 @@ import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude=MySQLAutoconfiguration.class)
|
||||
@ComponentScan(basePackages="com.baeldung.utils")
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
@ComponentScan(basePackages = "com.baeldung.utils")
|
||||
public class UtilsApplication {
|
||||
|
||||
@RolesAllowed("*")
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(UtilsApplication.class, args);
|
||||
}
|
||||
@RolesAllowed("*")
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(UtilsApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -13,37 +13,37 @@ import org.springframework.web.util.WebUtils;
|
||||
@Controller
|
||||
public class UtilsController {
|
||||
|
||||
@GetMapping("/utils")
|
||||
public String webUtils(Model model) {
|
||||
return "utils";
|
||||
}
|
||||
|
||||
@PostMapping("/setParam")
|
||||
public String post(HttpServletRequest request, Model model) {
|
||||
String param = ServletRequestUtils.getStringParameter(request, "param", "DEFAULT");
|
||||
|
||||
// Long param = ServletRequestUtils.getLongParameter(request, "param",1L);
|
||||
// boolean param = ServletRequestUtils.getBooleanParameter(request, "param", true);
|
||||
// double param = ServletRequestUtils.getDoubleParameter(request, "param", 1000);
|
||||
// float param = ServletRequestUtils.getFloatParameter(request, "param", (float) 1.00);
|
||||
// int param = ServletRequestUtils.getIntParameter(request, "param", 100);
|
||||
|
||||
// try {
|
||||
// ServletRequestUtils.getRequiredStringParameter(request, "param");
|
||||
// } catch (ServletRequestBindingException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
|
||||
WebUtils.setSessionAttribute(request, "parameter", param);
|
||||
model.addAttribute("parameter", "You set: "+(String) WebUtils.getSessionAttribute(request, "parameter"));
|
||||
return "utils";
|
||||
}
|
||||
|
||||
@GetMapping("/other")
|
||||
public String other(HttpServletRequest request, Model model) {
|
||||
String param = (String) WebUtils.getSessionAttribute(request, "parameter");
|
||||
model.addAttribute("parameter", param);
|
||||
return "other";
|
||||
}
|
||||
|
||||
@GetMapping("/utils")
|
||||
public String webUtils(Model model) {
|
||||
return "utils";
|
||||
}
|
||||
|
||||
@PostMapping("/setParam")
|
||||
public String post(HttpServletRequest request, Model model) {
|
||||
String param = ServletRequestUtils.getStringParameter(request, "param", "DEFAULT");
|
||||
|
||||
// Long param = ServletRequestUtils.getLongParameter(request, "param",1L);
|
||||
// boolean param = ServletRequestUtils.getBooleanParameter(request, "param", true);
|
||||
// double param = ServletRequestUtils.getDoubleParameter(request, "param", 1000);
|
||||
// float param = ServletRequestUtils.getFloatParameter(request, "param", (float) 1.00);
|
||||
// int param = ServletRequestUtils.getIntParameter(request, "param", 100);
|
||||
|
||||
// try {
|
||||
// ServletRequestUtils.getRequiredStringParameter(request, "param");
|
||||
// } catch (ServletRequestBindingException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
|
||||
WebUtils.setSessionAttribute(request, "parameter", param);
|
||||
model.addAttribute("parameter", "You set: " + (String) WebUtils.getSessionAttribute(request, "parameter"));
|
||||
return "utils";
|
||||
}
|
||||
|
||||
@GetMapping("/other")
|
||||
public String other(HttpServletRequest request, Model model) {
|
||||
String param = (String) WebUtils.getSessionAttribute(request, "parameter");
|
||||
model.addAttribute("parameter", param);
|
||||
return "other";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude=MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
public class WebjarsdemoApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
@@ -6,7 +6,7 @@ import org.springframework.context.ApplicationContext;
|
||||
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@SpringBootApplication(exclude=MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
public class Application {
|
||||
private static ApplicationContext applicationContext;
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
@SpringBootApplication(exclude=MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
@Import(GraphqlConfiguration.class)
|
||||
public class DemoApplication {
|
||||
|
||||
|
||||
@@ -10,11 +10,11 @@ public class FooService {
|
||||
|
||||
@Autowired
|
||||
private FooRepository fooRepository;
|
||||
|
||||
|
||||
public Foo getFooWithId(Integer id) throws Exception {
|
||||
return fooRepository.findOne(id);
|
||||
}
|
||||
|
||||
|
||||
public Foo getFooWithName(String name) {
|
||||
return fooRepository.findByName(name);
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
package org.baeldung.boot.exceptions;
|
||||
|
||||
public class CommonException extends RuntimeException{
|
||||
public class CommonException extends RuntimeException {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 3080004140659213332L;
|
||||
|
||||
public CommonException(String message){
|
||||
public CommonException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
package org.baeldung.boot.exceptions;
|
||||
|
||||
public class FooNotFoundException extends RuntimeException{
|
||||
public class FooNotFoundException extends RuntimeException {
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 9042200028456133589L;
|
||||
|
||||
public FooNotFoundException(String message){
|
||||
public FooNotFoundException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,6 @@ public class Foo implements Serializable {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
|
||||
public Foo(Integer id, String name) {
|
||||
super();
|
||||
this.id = id;
|
||||
|
||||
@@ -18,7 +18,7 @@ public class FooController {
|
||||
public Foo getFooWithId(@PathVariable Integer id) throws Exception {
|
||||
return fooService.getFooWithId(id);
|
||||
}
|
||||
|
||||
|
||||
@GetMapping("/")
|
||||
public Foo getFooWithName(@RequestParam String name) throws Exception {
|
||||
return fooService.getFooWithName(name);
|
||||
|
||||
@@ -39,21 +39,31 @@ public class GenericEntityController {
|
||||
|
||||
@RequestMapping("/entity/findby/{id}")
|
||||
public GenericEntity findById(@PathVariable Long id) {
|
||||
return entityList.stream().filter(entity -> entity.getId().equals(id)).findFirst().get();
|
||||
return entityList.stream()
|
||||
.filter(entity -> entity.getId()
|
||||
.equals(id))
|
||||
.findFirst()
|
||||
.get();
|
||||
}
|
||||
|
||||
@GetMapping("/entity/findbydate/{date}")
|
||||
public GenericEntity findByDate(@PathVariable("date") LocalDateTime date) {
|
||||
return entityList.stream().findFirst().get();
|
||||
return entityList.stream()
|
||||
.findFirst()
|
||||
.get();
|
||||
}
|
||||
|
||||
@GetMapping("/entity/findbymode/{mode}")
|
||||
public GenericEntity findByEnum(@PathVariable("mode") Modes mode) {
|
||||
return entityList.stream().findFirst().get();
|
||||
return entityList.stream()
|
||||
.findFirst()
|
||||
.get();
|
||||
}
|
||||
|
||||
@GetMapping("/entity/findbyversion")
|
||||
public ResponseEntity findByVersion(@Version String version) {
|
||||
return version != null ? new ResponseEntity(entityList.stream().findFirst().get(), HttpStatus.OK) : new ResponseEntity(HttpStatus.NOT_FOUND);
|
||||
return version != null ? new ResponseEntity(entityList.stream()
|
||||
.findFirst()
|
||||
.get(), HttpStatus.OK) : new ResponseEntity(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,9 +10,13 @@ public class MyHealthCheck implements HealthIndicator {
|
||||
public Health health() {
|
||||
int errorCode = check(); // perform some specific health check
|
||||
if (errorCode != 0) {
|
||||
return Health.down().withDetail("Error Code", errorCode).withDetail("Description", "You custom MyHealthCheck endpoint is down").build();
|
||||
return Health.down()
|
||||
.withDetail("Error Code", errorCode)
|
||||
.withDetail("Description", "You custom MyHealthCheck endpoint is down")
|
||||
.build();
|
||||
}
|
||||
return Health.up().build();
|
||||
return Health.up()
|
||||
.build();
|
||||
}
|
||||
|
||||
public int check() {
|
||||
|
||||
@@ -21,8 +21,7 @@ public class UserCombinedSerializer {
|
||||
@Override
|
||||
public void serialize(User user, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
|
||||
jsonGenerator.writeStartObject();
|
||||
jsonGenerator.writeStringField("favoriteColor",
|
||||
getColorAsWebColor(user.getFavoriteColor()));
|
||||
jsonGenerator.writeStringField("favoriteColor", getColorAsWebColor(user.getFavoriteColor()));
|
||||
jsonGenerator.writeEndObject();
|
||||
}
|
||||
|
||||
@@ -37,7 +36,8 @@ public class UserCombinedSerializer {
|
||||
public static class UserJsonDeserializer extends JsonDeserializer<User> {
|
||||
@Override
|
||||
public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
|
||||
TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
|
||||
TreeNode treeNode = jsonParser.getCodec()
|
||||
.readTree(jsonParser);
|
||||
TextNode favoriteColor = (TextNode) treeNode.get("favoriteColor");
|
||||
return new User(Color.web(favoriteColor.asText()));
|
||||
}
|
||||
|
||||
@@ -15,7 +15,8 @@ import java.io.IOException;
|
||||
public class UserJsonDeserializer extends JsonDeserializer<User> {
|
||||
@Override
|
||||
public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
|
||||
TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
|
||||
TreeNode treeNode = jsonParser.getCodec()
|
||||
.readTree(jsonParser);
|
||||
TextNode favoriteColor = (TextNode) treeNode.get("favoriteColor");
|
||||
return new User(Color.web(favoriteColor.asText()));
|
||||
}
|
||||
|
||||
@@ -15,8 +15,7 @@ public class UserJsonSerializer extends JsonSerializer<User> {
|
||||
@Override
|
||||
public void serialize(User user, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
|
||||
jsonGenerator.writeStartObject();
|
||||
jsonGenerator.writeStringField("favoriteColor",
|
||||
getColorAsWebColor(user.getFavoriteColor()));
|
||||
jsonGenerator.writeStringField("favoriteColor", getColorAsWebColor(user.getFavoriteColor()));
|
||||
jsonGenerator.writeEndObject();
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
@RestController
|
||||
@EnableAutoConfiguration(exclude=MySQLAutoconfiguration.class)
|
||||
@EnableAutoConfiguration(exclude = MySQLAutoconfiguration.class)
|
||||
@ComponentScan({ "org.baeldung.common.error", "org.baeldung.common.error.controller", "org.baeldung.common.properties", "org.baeldung.common.resources", "org.baeldung.endpoints", "org.baeldung.service", "org.baeldung.monitor.jmx", "org.baeldung.service" })
|
||||
public class SpringBootApplication {
|
||||
|
||||
|
||||
@@ -14,7 +14,8 @@ public class MonitoringConfig {
|
||||
|
||||
@Bean
|
||||
public JmxReporter jmxReporter() {
|
||||
JmxReporter reporter = JmxReporter.forRegistry(registry).build();
|
||||
JmxReporter reporter = JmxReporter.forRegistry(registry)
|
||||
.build();
|
||||
reporter.start();
|
||||
return reporter;
|
||||
}
|
||||
|
||||
@@ -16,7 +16,8 @@ public class LoginServiceImpl implements LoginService {
|
||||
|
||||
public boolean login(String userName, char[] password) {
|
||||
boolean success;
|
||||
if (userName.equals("admin") && "secret".toCharArray().equals(password)) {
|
||||
if (userName.equals("admin") && "secret".toCharArray()
|
||||
.equals(password)) {
|
||||
counterService.increment("counter.login.success");
|
||||
success = true;
|
||||
} else {
|
||||
|
||||
@@ -10,7 +10,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean;
|
||||
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
|
||||
|
||||
@EntityScan(basePackageClasses = Foo.class)
|
||||
@SpringBootApplication(exclude=MySQLAutoconfiguration.class)
|
||||
@SpringBootApplication(exclude = MySQLAutoconfiguration.class)
|
||||
public class Application {
|
||||
public static void main(String[] args) {
|
||||
System.setProperty("spring.config.name", "exception");
|
||||
|
||||
+4
-2
@@ -14,12 +14,14 @@ public class FooRepositoryImpl implements FooRepository {
|
||||
|
||||
@Override
|
||||
public void save(Foo foo) {
|
||||
sessionFactory.getCurrentSession().saveOrUpdate(foo);
|
||||
sessionFactory.getCurrentSession()
|
||||
.saveOrUpdate(foo);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Foo get(Integer id) {
|
||||
return sessionFactory.getCurrentSession().get(Foo.class, id);
|
||||
return sessionFactory.getCurrentSession()
|
||||
.get(Foo.class, id);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -20,6 +20,5 @@ public class Message {
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -17,12 +17,12 @@ import java.lang.reflect.Type;
|
||||
*
|
||||
*/
|
||||
public class MyStompSessionHandler extends StompSessionHandlerAdapter {
|
||||
|
||||
|
||||
private Logger logger = Logger.getLogger(MyStompSessionHandler.class);
|
||||
|
||||
|
||||
@Override
|
||||
public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
|
||||
logger.info("New session established : "+session.getSessionId());
|
||||
logger.info("New session established : " + session.getSessionId());
|
||||
session.subscribe("/topic/messages", this);
|
||||
logger.info("Subscribed to /topic/messages");
|
||||
session.send("/app/chat", getSampleMessage());
|
||||
@@ -41,15 +41,15 @@ public class MyStompSessionHandler extends StompSessionHandlerAdapter {
|
||||
|
||||
@Override
|
||||
public void handleFrame(StompHeaders headers, Object payload) {
|
||||
Message msg = (Message)payload;
|
||||
logger.info("Received : "+ msg.getText()+ " from : "+msg.getFrom());
|
||||
Message msg = (Message) payload;
|
||||
logger.info("Received : " + msg.getText() + " from : " + msg.getFrom());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* A sample message instance.
|
||||
* @return instance of <code>Message</code>
|
||||
*/
|
||||
private Message getSampleMessage(){
|
||||
private Message getSampleMessage() {
|
||||
Message msg = new Message();
|
||||
msg.setFrom("Nicky");
|
||||
msg.setText("Howdy!!");
|
||||
|
||||
@@ -19,9 +19,9 @@ public class StompClient {
|
||||
public static void main(String[] args) {
|
||||
WebSocketClient client = new StandardWebSocketClient();
|
||||
WebSocketStompClient stompClient = new WebSocketStompClient(client);
|
||||
|
||||
|
||||
stompClient.setMessageConverter(new MappingJackson2MessageConverter());
|
||||
|
||||
|
||||
StompSessionHandler sessionHandler = new MyStompSessionHandler();
|
||||
stompClient.connect(URL, sessionHandler);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user