Σάββατο 23 Οκτωβρίου 2021

Spring Certification: Spring Boot Testing

When do you want to use @SpringBootTest annotation?
  • When we want to load whole ApplicationContext for our tests
  • Mostly when running a JUnit integration test
  • @SpringBootTest will search for a main configuration class or @SpringBootApplication annotated class upwards the project structure tree, and start a Spring application on a mock or running environment, with full application context - no slicing.
  • To use it:
    • JUnit 4 - Add @RunWith(SpringRunner.class) also
    • JUnit 5 - Runner is already included in the annotation

What does @SpringBootTest auto-configure?
  • @SpringBootTest  searches for  @SpringBootApplication / @SpringBootConfiguration, which contains @EnableAutoConfiguration, which triggers Spring AutoConfiguration mechanism.

  • So it uses all xxxAutoConfiguration classes in spring.factories, which autoconfigure all beans needed, according to what exists in the classpath

  • Alternatively, @SpringBootTest(classes = CustomApplication.class) sets a specific main configuration class

  • Also, @SpringBootTest(properties = "spring.main.web-application-type=reactive") takes in account specific properties file



What dependencies does spring-boot-starter-test brings to the classpath?
  • Spring Test
  • Spring Boot Test modules
  • JSONPath
  • JUnit,
  • AssertJ
  • Mockito
  • Hamcrest
  • JSONassert


How do you perform integration testing with @SpringBootTest for a web application?
  • Integration tests should be performed in a full running server environment, so we use:
    • @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) (or defined port)
    • And a fully configured TestRestTemplate or WebTestClient to act a REST client for our tests 
  • Integration tests could be run in a mock servlet environment, that by default @SpringBootTest bootstraps. The original application context will be loaded. For actual test methods, we will use MockMvc. Generally, note that there are no actual mocks of any classes. Also we don't need to use @MockBean or mocks like in @WebMvcTest 




  • Additionally, we might need a test-only property file, so we use @TestPropertySource. As mentioned, the @Value annotations will now be injected from our test property file.



When do you want to use @WebMvcTest? What does it auto-configure?
  • When we want to test the web slice of an application, particularly the behavior of the controllers interacting with the outer world.
  • By default, it autoconfigures all Spring beans referring to the web part, and specifically:
    • @Controller
    • @ControllerAdvice
    • @JsonComponent
    • @WebMvcConfigurer
    • and more
  • Can autoconfigure specific controller with: @WebMvcTest(SomeController.class)
  • Except for @Controllers setup, we must mock their dependencies with use of @MockBean
  • Autoconfigures MockMvc, to use in performing mock web tests


What are the differences between @MockBean and @Mock?
  • @Mock  is used to create mocks of any class, generally method-wise, while @MockBean to replace Spring bean context-wise
  • @Mock needs @RunWith(MockitoJUnitRunner.class) (Mockito library), while @MockBean needs @RunWith(SpringRunner.class) (spring-boot-test)
  • @Mock creates a Mockito mock, while @MockBean creates a Mockito mock and injects it into the Application Context
  • In order for a @Mock to be injected in its container class, need to use @InjectMocks on container class reference


When do you want @DataJpaTest for? What does it auto-configure?
  • Use for test slicing, particularly for testing of Spring beans that talk to a database (Entities, Repositories)
  • Configures in-memory database for testing
  • Loads in Application Context: @Entities, @Repositories, @TestEntityManager

Παρασκευή 22 Οκτωβρίου 2021

Spring Certification: Spring Boot Actuator

What value does Spring Boot Actuator provide?
  • Out-of-the-box production-ready features, like monitoring, metrics, health checks, audit events and more
  • Provided with spring-boot-starter-actuator dependency
  • Access through HTTP endpoints, like /actuator/health



What are the two protocols you can use to access actuator endpoints?
  • HTTP
  • JMX


What are the actuator endpoints that are provided out of the box?

  • /actuator:  provides a hypermedia-based discovery page for all the other endpoints (requires spring-boot-starter-hateoas)
  • /health: application health checks
  • /configprops:  lists all the configuration properties that are defined by the @ConfigurationProperties beans
  • /beans:  lists all Spring beans
  • /env: exposes all the properties from the Spring Environment abstraction. Displays application properties, active profiles and system environment variables
  • /httptrace: Shows most recent HTTP requests/responses
  • /info: general application info
  • /metrics: memory, performance, processor, garbage collection, and HTTP requests
  • /loggers:  view logs (also change without restarting app)



What is info endpoint for? How do you supply data?

  • Actuator's info endpoint is used to project user-customized application data, like application name, version, description, java runtime and more
  • The endpoint is exposed through HTTP (/actuator/info) or JMX (org.springframework.boot/Endpoint/Info)
  • To supply data, in application.properties define info.app.name/description/version or info.java-vendor. Alternatively, create a Component implementing InfoContributor

How do you change logging level of a package using loggers endpoint?
  • Execute a POST in /actuator/loggers endpoint and specific package, like: 
    • curl -i -X POST -H 'Content-Type: application/json' -d '{"configuredLevel": "INFO"}' http://localhost:8080/actuator/loggers/com.code.in.packets.package1.logging
  • Also, make to enable loggers endpoint:
    • management.endpoints.web.exposure.include=loggers
                management.endpoint.loggers.enabled=true

 

How do you access an endpoint using a tag?

  • Using syntax: /actuator/metrics/<metric>?tag=<key>:<value>
  • Example listing all GET requests that resulted in a server error: 
    • /actuator/metrics/http.server.requests?tag=outcome:SERVER_ERROR&tag=method:GET


What is metrics for?
  • Actuator metrics are implemented by Micrometer
  • Provide information about: memory usage, CPU usage, threads, garbage collection, application uptime, heap size, site-visited count and more
  • Need to explicitly enable in properties: management.endpoints.web.exposure.include=metrics


How do you create a custom metric?

  • Inject a MeterRegistry dependency in a Component
  • Use MeterRegistry's methods, like timer, counter, gaugeNewCollection and more to display desired info, like:
    • meterRegistry.gaugeCollectionSize("employeesList.size", Tags.empty(), this.employeesList)
    • meterRegistry.counter("<metric-name>", "<key>", <value>).increment(); 

What is Health Indicator?
  • HealthIndicator API and its endpoint "/actuator/health" is used to produce information about application status and overall health 
  • External systems can consume it in order to decide any time if we have a fault tolerant and durable application
  • The endpoint provides all Health Indicators that are set programmatically as components that implement HealthIndicator and override health method
  • Health Indicators are provided/autoconfigured by Spring Actuator, when relevant dependencies are found

What are the Health Indicators that are provided out of the box?
  • ApplicationHealthIndicator, should always be UP
  • DiskSpaceHealthIndicator, DOWN if low disk space is available
  • DataSourceHealthIndicator, UP if connection successful, otherwise DOWN.
  • JmsHealthIndicator, UP if connection with message broker successful, otherwise DOWN
  • Similar for Mail, Redis, Neo4J, Solr and more



    What is the Health Indicator status?
    What are the Health Indicator statuses that are provided out of the box?
    • All Health Indicators return a health status if triggered (from overwritten health method), that are aggregated and displayed in /health endpoint. These statuses are:
    • UP (200)
    • DOWN (503)
    • UNKNOWN (200)
    • OUT_OF_SERVICE (503)


    How do you change the Health Indicator status severity order?
    • Configure "management.health.status.order" property, like:
      • management.health.status.order=DOWN, OUT_OF_SERVICE, UNKNOWN, UP

    Why do you want to leverage 3rd-party external monitoring system?
    • Necessity: Decoupling code from system monitoring utilities, and having an extra system for alert, data/visitor visualizations, and more
    • Easy with Spring: Spring Actuator uses Micrometer that is a facade for multiple external monitoring systems, like Elastic, Atlas, KairosDB and more. We only need to import dependency with groupId = io.micrometer, and artifactId = micrometer-registry-${external-monitoring-system}


    -----------------------------------------------------------------------------------------------------


    Questions from EDU-1202 exam (2021)


    Actuator JMX endpoints can also be turned on for HTTP
    • True
    Actuator metrics can be leveraged by third-party providers for purposes of visualization
    • True
    Providers (Prometheus, Grafana, etc) can be adjusted easily by declaring dependency in pom.xml
    • True

    Πέμπτη 21 Οκτωβρίου 2021

    Spring Certification: Spring Boot Auto Configuration

    How does Spring Boot know what to configure?
    • These classes contain ConditionalOn.. classes that scan classpath resources and register beans, according to starters and dependencies that user introduced in POMs
    • Spring Boot checks for the presence of a META-INF/spring.factories file within your published jar. The file should list your configuration classes under the EnableAutoConfiguration key, as shown in the following example:
      • org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
        com.code.in.packets.autoconf.SomeAutoConfiguration1,\
        com.code.in.packets.autoconf.SomeAutoConfiguration2
    • See all ConditionalOn classes
    • Using @Profile("some-profile") on a @Bean, and then load this profile

    • Using @Conditional("<some-class>") on a @Bean




    What does @EnableAutoConfiguration do?

    • Applied in Application/Main class of Spring application
    • In Spring Boot application, already included in @SpringBootApplication annotation
    • Responsible for kick-starting autoconfiguration process, by
      • @AutoConfigurationPackage
        • Importing AutoConfigurationPackages.Registrar, that registers a bean which provides Bean list for Spring boot to use internally, in spring-boot-autoconfigure package
      • @Import(EnableAutoConfigurationImportSelector.class)
        • Imports AutoConfigurationImportSelector that aggregates all spring.factories
    • Can exclude some autoconfiguration class, like: @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) in our @Configuration class



    What does @SpringBootApplication do?

    • Applied only in root package class, and contains below annotations:
    • @EnableAutoConfiguration: enables Spring Boot’s auto-configuration mechanism
    • @ComponentScan: enable @Component scan on the package where the application is located
    • @Configuration: allow to register extra beans in the context or import additional configuration classes

    Does Spring Boot do component scanning? Where does it look by default?
    • Yes, @ComponentScan or @SpringBootApplication enables component scanning.
    • By default, it scans for components in whole package (and subpackages) of the class with @SpringBootApplication
    • If no component scanning is set, it only scans the package of the main class
    • @ComponentScan is also used to specify base packages and base package classes using thebasePackageClasses or basePackages attributes


    How are DataSource and JdbcTemplate auto-configured?
    • DataSource 
      •  with DataSourceAutoConfiguration class from spring-boot-autoconfigure package.
      • that retrieves properties spring.datasource.url, spring.datasource.username, spring.datasource.password from application.properties or yml file.
    • JdbcTemplate
      • with JdbcTemplateAutoConfiguration, that contains:
      • @ConditionalOnClass(value={javax.sql.DataSource.class,org.springframework.jdbc.core.JdbcTemplate.class})
        • If DataSource class exists in classpath, only then configure JdbcTemplate
      • @ConditionalOnSingleCandidate(value=javax.sql.DataSource.class)
        • We need only one candidate
      • @AutoConfigureAfter(value=DataSourceAutoConfiguration.class) 
        • First configure DataSource, and only then JdbcTemplate 

    What is spring.factories file for?
    • spring.factories contains auto-configuration classes needed for the AutoConfiguration mechanism of Spring
    • @EnableAutoConfiguration eventually gathers all spring.factories files of all project modules/packages and aggregates them into one.
    • A spring.factories contains an EnableAutoConfiguration key with values as the list of auto-configuration classes, and resides under META/INF directory
    • spring.factories should be used when we want to set default components globally for our app. Thus the need for @Autowire-ing a dependency disappears. But of course, this default behavior can later be overwritten with some @Bean/@Configuration


    How do you customize Spring Boot auto configuration?
    • To create our own auto-configuration: 
      • add a spring.factories in META-INF, with content:
      • org.springframework.boot.autoconfigure.EnableAutoConfiguration= com.myapp.package1.autoconfigure.MyDataSourceAutoConfiguration, com.myapp.package2.autoconfigure.MyJpaAutoConfiguration
      • Implement above classes as @Configurations accordingly to specific needs
      • Disable loading of auto-configuration class for DataSource loading:  @EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class}) 


    What are the examples of @Conditional annotations? How are they used?

    Conditional classes are used from within AutoConfiguration classes to load conditionally classpath resources :
    • ConditionalOnBean - Spring Bean must be registered
    • ConditionalOnMissingBean - Spring Bean must not be registered
    • ConditionalOnClass - Class must exist in classpath
    • ConditionalOnMissingClass - Class must not exist in classpath
    • ConditionalOnExpression - spEL expression must result to true
    • ConditionalOnJava - Java JDK in certain version must exist
    • ConditionalOnJndi - JNDI location should exist
    • ConditionalOnProperty - property must exist
    • ConditionalOnResource - resource must exist

    Τετάρτη 20 Οκτωβρίου 2021

    Spring Certification: Spring Boot Basics

    What is Spring Boot?
    • Extension of Spring Framework
    • Build fast production-ready applications, by:
    • providing auto-configurated dependencies
    • starter POMs (easy dependency management)
    • devTools (live code reload)
    • Fit for building apps in microservice architecture


    What are the advantages of using Spring Boot?

    • Starter POMs: provide commonly used dependencies with correct versions and transitive dependencies
    • Embedded servlet containers (tomcat, jetty..), no need for WAR, packaging and deploying manually
    • Automatic Configuration: out of the box dependencies, but also configurable
    • Facilitates testing - provides default setup for unit IT tests
    • Solves boilerplate code in Spring projects (no XML)
    • Easily set  development and production profiles
    • Non-functional requirements: Security, Metrics, Externalized configuration and more


    Why is it opinionated?
    • Convention over configuration principle is followed, meaning that framework tries to understand what to load, depending on what dependencies the developer has entered
    • Above approach can be edited


    What things affect what Spring Boot sets up?
    1. Dependencies are set via starter POMs and/or additional by hand
    2. Spring Boot's autoconfigure module scans what there is on the classpath, and then employs Spring beans to integrate all dependencies (e.g. Spring MVC, Spring Data JPA, etc). This is done with use of @ConditionalOn.. inside AutoConfiguration classes.
    3. Furthermore, developer can set @ConditionalOn.. in his beans


        @ConditionalOn.. classes:

    • ConditionalOnBean - Spring Bean must exist
    • ConditionalOnMissingBean - Spring Bean must not exist
    • ConditionalOnClass - Class must exist
    • ConditionalOnMissingClass - Class must not exist
    • ConditionalOnExpression - spEL expression must result to true
    • ConditionalOnJava - Java JDK in certain version must exist
    • ConditionalOnJndi - JNDI location should exist
    • ConditionalOnProperty - property must exist
    • ConditionalOnResource - resource must exist


    What is a Spring Boot starter? Why is it useful?

    • Spring Boot starters are sets of dependency descriptors that define all correct transitive dependencies and versions needed to provide a specific technology to include and use in applications. All official starters follow this pattern: spring-boot-starter-*
    • Developers can focus on business logic, not worrying much about dependency management.
    • Ensures no dependencies are missing and that all have versions that are compatible together.


    Spring Boot supports both properties and YML files. Would you recognize and understand them if you saw them?
    • Spring provides option for externalization of configuration by Properties file or YML
    • YML is derived from JSON and is enabled when snakeYAML dependency is present
      • Recognizable from its hierarchical data structure


    Can you control logging with Spring Boot? How?
    • Logging library:
      • If spring-boot-starter-web is used, by default Spring uses Commons Logging API, and Apache Logback as reference implementation. To change that, we need to exclude Logback in pom, and include another compatible e.g. Log4J
    • Logging levels:
      • In application properties use logging.level.root=<level> (application-wise).  Use debug=true to enable DEBUG mode globally
      • or com.app.package1=<level> (package-wise)
      • Alternatively, above can apply in a logback-spring.xml file
      • From VM options like: -Dlogging.level.org.springframework=DEBUG

    • Logging output: Use logging.file or logging.path in application properties


    Where does Spring Boot look for application.properties file by default?
    1. In /config directory (outside of classpath/jar)
    2. In application directory (outside of classpath/jar)
    3. In /config directory of classpath (in jar)
    4. In classpath root directory (in jar)



    How do you define profile specific property files?
    • application-{profile}.yml or application-{profile}.properties
    • If a property is not found in profile-specific file, it loads from the application.properties or application-default.properties (same for yml)



    How do you access the properties defined in the property files?
    • In @Configuration class, annotate itself with @PropertySource("app.properties") and then annotate fields with @Value("app.some.property")
    • Alternatively, in Class1 add annotation @ConfigurationProperties(prefix = "app.some"), and then refer to field as "property". Finally, access property value in a second @Configuration class with @EnableConfigurationProperties(Class1.class)
    • @Autowire Spring's Environment, and access property with environment.getProperty("app.some.property")



    What properties do you have to define in order to configure external MySQL?
    • spring.datasource.url=jdbc:mysql://<host>:<port>/<databaseName>
    • spring.datasource.username=<username>
    • spring.datasource.password=<password>
    • spring.datasource.driver-class-name=com.mysql.jdbc.Driver


    How do you configure default schema and initial data?
    • Configure data.sql and schema.sql in /resources 
    • In properties: spring.datasource.initialization-mode=always
    • If using hibernate, spring.jpa.hibernate.ddl-auto=none
    • Spring loads according to platform set and loads data-{platform}.sql and schema-{platform}.sql. Platform is defined in property spring.datasource.platform=<vendor-platform>, e.g. mysql


    What is a fat jar? How is it different from the original jar?
    • An executable jar containing all compiled classes and resources, along with dependencies as nested jars
    • project-1.2.3-SNAPSHOT.jar is the Fat jar, while inside it project-1.2.3-SNAPSHOT.jar.original is the original jar. 
    • To create a Fat jar, spring-boot-maven-plugin is needed to insert original jar in Fat jar. 
    • Fat jar is executable by default with java -jar project-1.2.3-SNAPSHOT.jar, while original is not.


    What is the difference between an embedded container and a WAR?
    • Embedded container is used to run a single application's executable jar, and resides in jar itself as a dependency
      • To set up, use maven dependencies spring-boot-starter-web (provides embedded tomcat) and spring-boot-maven-plugin with repackaging goal (to integrate original jar in executable/fat jar)
    • WAR needs to be deployed in an Application Server, where many other war files (applications) can co-exist
      • To set up, use <packaging>war</packaging>, spring-boot-starter-web dependency and spring-boot-starter-tomcat with provided scope

    What embedded containers does Spring Boot support?
    • Tomcat 
      • Default with spring-boot-starter-web
    • Jetty
      • First must exclude default Tomcat with <exclusion> tag
      • Set spring-boot-starter-jetty dependency
    • Undetow
      • Same setup logic as Jetty



















    Σάββατο 16 Οκτωβρίου 2021

    Spring Certification: Testing

    What type of tests typically use Spring?
    • Unit testing
    • Integration testing

    How can you create a shared application context in a JUnit integration test?
    • Enable Spring TestContext Framework to load shared application context, using below JUnit runner:
    • @RunWith(SpringRunner.class)
      @ContextConfiguration(classes = OrderConfiguration.class)
      public class OrderServiceTests implements ApplicationContextAware { }

    • Variation of above:
    • @ContextConfiguration(classes = OrderConfiguration.class)

      public class OrderServiceTests implements ApplicationContextAware extends AbstractJUnit4SpringContextTests { }

    • Use @DirtiesContext to re-create context for next tests


    When and where do you use @Transactional in testing?
    • Method level:
      • @Transactional - Method runs in own transaction rollbacked at the end by default
      • To override above, use @TransactionConfiguration(defaultRollback = false) in class level
    • Class level:
      • @Transactional - All methods run in own transaction rollbacked at the end by default
      • To override above, use @Rollback(false) or @Commit in desired method


    How are mock frameworks such as Mockito or EasyMock used?
    • Declare the mock:
      • OrderBook mockOrderBook = mock(OrderBook.class);
      • Or using annotation @Mock:
        • Use @RunWith(MockitoJUnitRunner.class) in class method
        • Or MockitoAnnotations.initMocks(this) in before / setup method
      • Or (Spring Boot), use @MockBean which mocks Spring beans
    • Inject mock in related component
    • Set behaviour when called:
    • when(mockOrderBook.findAllForBook()).thenReturn(books);
    • Test and verify with Assertions

    How is @ContextConfiguration used?
    • In Spring, it's used for loading an ApplicationContext, along with a JUnit runner
    • Example 1: 
      • @RunWith(SpringJUnit4ClassRunner.class)
        @ContextConfiguration(classes={BookConfig.class})
        public class BookConfigTest {}
    • Example 2:
      • @RunWith(SpringJUnit4ClassRunner.class)
        @ContextConfiguration
        public class BookConfigTest {}
      • Loads context from BookConfigText-context.xml classpath file

    • In Spring Boot, @SpringBootTest includes @ContextConfiguration annotation


    How does Spring Boot simplify writing tests?
    • Adding dependency spring-boot-starter-test provides:
        spring-boot-test, spring-boot-test-autoconfigure     which provide below:


        JUnit: The de-facto standard for unit testing Java applications.
        Spring Test & Spring Boot Test: Utilities and integration test support for Spring Boot applications.
        AssertJ: A fluent assertion library.
        Hamcrest: A library of matcher objects (also known as constraints or predicates).
        Mockito: A Java mocking framework.
        JSONassert: An assertion library for JSON.
        JsonPath: XPath for JSON.

    • Instantiate dependencies by using new or mock, no need to involve Spring

    • Integration testing with Spring ApplicationContext with or without requiring deployment (MockMvc)

    • Spring Boot: Detects automatically test configuration without @ContextConfiguration and declaring @Configuration classes
         Detects classes @SpringBootApplication or @SpringBootConfiguration

    • Spring Boot: Use *Test annotations to introduce test slicing. 
        Example: @DataJpaTest, @WebMvcTest

    • Spring’s test framework caches application contexts between tests.
        Therefore, as long as your tests share the same configuration (no matter how it is discovered),
        the potentially time-consuming process of loading the context happens only once.

    • @TestConfiguration: Can exclude loading automatically configuration classes belonging in src/test/java.
        Then, can decide to @Import or not the specific configuration



    What does @SpringBootTest do?
    How does it interact with @SpringBootApplication and@SpringBootConfiguration?

    • Used to load a full Application Context, either running a server or in mock environment
    • Includes option to load specific properties

    • SpringBootTest annotation traverses related class package upwards until a @SpringBootConfiguration is located
    • Note that @SpringBootApplication included @SpringBootConfiguration 
    • It then constructs a whole Application Context

    Πέμπτη 7 Οκτωβρίου 2021

    Spring Certification: Security

    What are authentication and authorization? Which must come first?
    • Authentication is the process of deciding if the user making a request, is accepted to use the application resources
      • Validation of credentials
      • Validation of the content of Authentication Header in request
      • Validation of the JSESSION cookie
    • Authorization is the process of deciding if an authenticated user can have access to a specific application resource
      • Happens in web request level or method level
    • Authentication comes first.


    Is security a cross cutting concern? How is it implemented internally?
    • Yes
    • In web request and method level:
      • Web request level
        • Register a springSecurityFilterChain (using AbstractSecurityWebApplicationInitializer base class or xml)
        • DelegatingFilterProxy will ensure this filter will be used before any else
        • and delegates to AccessDecisionManager, which delegates to a list of configured AccessDecisionVoters
        • Access to particular resource is granted or denied
      • Method level: Implemented with AOP proxies that check user permission for resource


    What is the delegating filter proxy?

    • Servlet filter that allows passing control to Filter classes that have access to the Spring application context.
    • Specifically, requests are propagated from DelegatingFilterProxy to a registered FilterChainProxy which contains our security logic
    • Spring security is configured by declaring a filter DelegatingFilterProxy in web.xml 


    What is the security filter chain?
    • DelegatingFilterProxy delegates to springSecurityFilterChain which is a FilterChainProxy
    • Contains security process-handling logic
    • Contains Filters in a chain, registered as Spring beans
    • Responsibilities: authentication, authorization, logout, maintain Security context
    • Examples of filters:
      • SecurityContextPersistenceFilter (restores Authentication from JSESSIONID) 
      • UsernamePasswordAuthenticationFilter (performs authentication)
      • ExceptionTranslationFilter (catch security exceptions from FilterSecurityInterceptor)
      • FilterSecurityInterceptor (may throw authentication and authorization exceptions) 

    What is a security context?

    • The SecurityContext is used to store the details of the currently authenticated user (principle).
    • The SecurityContextHolder helper class provides access to SecurityContext
    • Thus, user details can be retrieved.
    • By default, a ThreadLocal object is utilized to store the SecurityContext, so the security context is available to methods in the same execution thread.


    What does the ** pattern in an antMatcher or mvcMatcher do?
    • Indicates any path (after the path before **) is valid for matching, example:
    • /rest/books/**

    Why is the usage of mvcMatcher recommended over antMatcher?

    • Generally mvcMatcher is more secure than an antMatcher. (Spring MVC’s HandlerMappingIntrospector)
      • Also, MvcMatcher can also restrict the URLs by HTTP method

      • Semantics:
        • antMatchers("/books") matches only the exact URL
        • mvcMatchers("/books") matches /books, and  /books/, /books.html, /books.xyz    

      Does Spring Security support password encoding?
      • Yes, provides password encoding using the PasswordEncoder interface. Note we can only encode the plain text to password, and not the opposite.



      Why do you need method security? What type of object is typically secured at the method level (think of its purpose not its Java type).

      • Method security is needed to apply security logic to lower level methods. It also provides an extra layer of security, along with web request level
      • Method security is applied with Spring AOP proxies
      • Spring Security provides below types of annotations:

        • Spring Security’s @Secured
        • JSR-250’s @RolesAllowed
        • @PreAuthorize /@PostAuthorize
        • @PreFilter / @PostFilter

      What do @PreAuthorized and @RolesAllowed do? What is the difference between them?
      • @PreAuthorized: Restricts access to a method before invocation based on the result of evaluating spEL expression, like: 
        • @PreAuthorize("hasRole(’ADMIN’) or hasRole(’ADMIN2’)")
          public void createBookEntry(Book book){}
      • @RolesAllowed:Same as above, but does only permit a role reference, not an expression
        • @RolesAllowed("ROLE_ADMIN")
             public User findBookById(Long id) {}

      How are these annotations implemented?
      • @PreAuthorized: 
        • Part of Spring Security framework
        • Spring recognizes these annotated method using Spring AOP proxies
        • To enable above, set @EnableGlobalMethodSecurity(prePostEnabled = true)
      • @RolesAllowed: 
        • Originates in the JSR-250 Java security standard
        • Library must be in classpath
        • To enable above, set @EnableGlobalMethodSecurity(jsr250Enabled=true)

      In which security annotation, are you allowed to use SpEL?
      • @PreAuthorized
      • @PostAuthorized
      • @PreFilter
      • @PostFilter

      Τετάρτη 6 Οκτωβρίου 2021

      Spring Certification: Spring MVC REST

      What does REST stand for?
      • REpresentational State Transfer (REST) is a stateless client-server architecture in which the web services are viewed as resources that can be identified by their URIs

      • RE refers to the variety of representation types, such as XML, JSON, and more

      • REST is not protocol-specific, however people link it to HTTP

      • REST is not secure by default

      • Lack of statefulness enables scalability. Many concurrent clients can access a REST endpoint.



      What is a resource?

      • Web resources are provided by a Web Service, in a textual representation and can be read and modified with a stateless protocol and a predefined set of operations (GET, POST, .. )
      • Resource is identified by a unique URI
      • Resource can be image, file, html, etc..
      • example: www.codeinpackets.com/certifications/Spring/5


      Is REST secure? What can you do to secure it?

      • No
      • Connection Security level:  Api should provide only HTTPS endpoints to ensure communication is encrypted with SSL/TLS
      • API Access Control level:
        • HTTP Basic Auth - credentials sent in HTTP header encoded
        • JSON Web Tokens - credentials as JSON data structures (can be signed cryptographically)
        • OAuth - for authentication and authorization


      What are safe REST operations?
      • Safe operations do not alter the state of the resources on the server
      • GET, HEAD, OPTIONS, TRACE


      What are idempotent operations? Why is idempotency important?
      • GET, PUT, DELETE
      • Idempotent operations cannot alter resources, no matter how many times they are executed



      Is REST scalable and/or interoperable?
      • Yes, both scalable and interoperable
      • Scalable because the server can send a response to client request regardless of any session afinity or sticky session, as such there is not. This lack of session information enables serving a large quantity of request simultaneously.
      • Interoperable: REST is platform independent like the web services and language independent. CRUD can be freely implemented by any language. Also, supports many data formats, like xml,j son


      Which HTTP methods does REST use?

      • GET               Read
      • PUT                Update/Replace
      • PATCH         Partial Update/Modify
      • DELETE       Delete


      What is an HttpMessageConverter?

      • Used to marshall and unmarshall Java Objects to and from JSON, XML, etc  over HTTP.
      • Each HttpMessageConverter implementation has one or several associated MIME Types.
      • MappingJackson2HttpMessageConverter is used for JSON format
      • When receiving a new request, Spring matches the "Content-Type" header with "consumes" attribute of @RequestMapping, to decide what HttpMessageConverter to use for reading the message
      • and matches “Accept” header with "produces" attribute of @RequestMapping, to determine the media type that it needs to respond with. It will then try to find a registered converter that's capable of handling that specific media type. Finally, it will use this to convert the entity and send back the response.
      • More: https://codingnconcepts.com/spring-boot/jackson-json-request-response-mapping/

      Is @Controller a stereotype? Is @RestController a stereotype?

      • @Controller, @Repository and @Service are annotated with @Component, so they are stereotypes. @RestController is annotated with @Controller, so it's a stereotype.
      • The @RestController annotation in Spring is essentially just a combination of @Controller and @ResponseBody.
      • Stereotype annotations are markers for any class that fulfills a role within an application. This helps remove, or at least greatly reduce, the Spring XML configuration


      What is the difference between @Controller and @RestController?

      • The @RestController annotation in Spring is essentially just a combination of @Controller and @ResponseBody.
      • All @RestController handler methods return straight to the response body, not in a Model or View in MVC terms

      When do you need to use @ResponseBody?

      • The @ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object.
      • Use in class level in @Controller, when we need a REST controller
      • Use in method level to return serialized data to response body (using HttpMessageConverter), instead of just passing the model and view.

      What are the HTTP status return codes for a successful GET, POST, PUT or DELETE operation?

      • PUT - 200 (OK), 201(Created), 204 (No Content)
      • DELETE - 20, 202(Accepted), 204
      • POST - 201
      • GET - 200
      •  Generally, response codes:
        • 1**: Informs about ongoing request process
        • 2**: Success (parsed correctly and accepted)
        • 3**: Redirection must take place for completion
        • 4**: Client error - Invalid request
        • 5**: Server error - Server unavailable


      When do you need to use @ResponseStatus?
      • Annotate exception class to define returning error code and reason
      • Annotate controller methods to override original response status (also disables DispatcherServlet from acquiring a view)


      Where do you need to use @ResponseBody? What about @RequestBody?
      • @RequestBody annotation maps the HttpRequest body to a transfer or domain object, enabling automatic deserialization of the inbound HttpRequest body onto a Java object.



      What Spring Boot starter would you use for a Spring REST application?
      • The spring-boot-starter-web is a starter for building web, including RESTful, applications using Spring MVC. It uses Tomcat as the default embedded container.


      If you saw an example using RestTemplate, would you understand what it is doing?
      • RestTemplate implements a synchronous HTTP client that facilitates sending and receiving requests in a RESTful manner.
      • URI template creation and encoding is supported
      • Conversion between domain and HTTP is supported
      • Provides a high-level API for setting up requests, for example: getForObject, getForEntity, headForHeaders, postForObject
      • Example:






      -----------------------------------------------------------------------------------------------------


      Questions from EDU-1202 exam (2021)


      Does Spring implements JAX-RS, or provides some implementation of it, or it is irrelevant?
      • Spring's REST does not relate to JAX-RS specification.

      Spring Certification: Spring MVC Basics

      What is the @Controller annotation used for?
      • Specialization of @Component annotation, used to define a Controller class in terms of MVC pattern
      • DispatcherServlet recognizes controller classes having this annotation,
      • and maps incoming request to correct controller, by reading @RequestMapping accompanying annotation

      How is an incoming request mapped to a controller and mapped to a method?
      • Request reaches application server which calls DispatcherServlet
      • DispatcherServlet uses HandlerMapping components to gather all controllers (HandlerMapping already has scanned all @Controllers from classpath, on init)
      • DispatcherServlet takes in account the @RequestMapping's path among other params to define the correct class/method.
      • DispatcherServlet uses HandlerAdapter to call controller method's execution


      What is the difference between @RequestMapping and @GetMapping?
      • @GetMapping annotation is a composed annotation equal to @RequestMapping(method = RequestMethod.GET)
      • Other specializations of @RequestMapping: @[Put/Delete/Post]Mapping
      • @GetMapping does not support attribute "consumes" as @RequestMapping does.


      What is @RequestParam used for?
      • @RequestParam is used for binding web request parameters to controller's method parameters
      • Example: public String getAge (@RequestParam("age") int age, ...)
      • Can use attributes like value, required, defaultValue, and Java 8's Optional

      What are the differences between @RequestParam and @PathVariable?

      • @PathVariable maps parts of URI with controller method parameters
      • example: @GetMapping("book/orders/{orderId}")
        public String getBookOrderById(@PathVariable("orderId") int orderId, .. , ..)
      • @RequestParam is used for binding web request parameters to controller's method parameters
      • @RequestParam provides defaultValue, while @PathVariable does not

      What are the ready-to-use argument types you can use in a controller method?

      • WebRequest, NativeWebRequest
      • javax.servlet.ServletRequest, javax.servlet.ServletResponse
      • javax.servlet.http.HttpSession
      • java.security.Principal
      • @RequestBody
      • @RequestHeader
      • More: https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-methods

      What are some of the valid return types of a controller method?
      • @ResponseBody
      • String (return name of view, handled by ViewResolver)
      • View
      • Map
      • ModelAndView
      • HttpEntity (construct full http response with headers and body)
      • ResponseEntity (also add http error code)
      • HttpHeaders (construct response with only headers)
      • void




      -----------------------------------------------------------------------------------------------------


      Questions from EDU-1202 exam (2021)


      How can this method return data as JSON?


      • Add @ResponseBody above method
      • Tip: Generally study return types and cases (no "null" return is correct, but Void, Model, View, ModelAndView, HttpResponse, ...)


      Does / can Spring MVC use REST ?
      • The way the HTTP response body is created is the only difference between a traditional Spring MVC controller and the RESTful controller. The traditional MVC controller is dependent on the View technology, but the RESTful controller returns the object as JSON inside the HTTP response