Εμφάνιση αναρτήσεων με ετικέτα HTTP. Εμφάνιση όλων των αναρτήσεων
Εμφάνιση αναρτήσεων με ετικέτα HTTP. Εμφάνιση όλων των αναρτήσεων

Πέμπτη 19 Δεκεμβρίου 2024

REST vs SOAP vs Spring

 






  • @ResponseEntity automatically serializes Java objects to JSON
  • Spring uses the HttpMessageConverter to serialize the body of the ResponseEntity into the appropriate format (e.g., JSON, XML, plain text) based on the client's Accept header.

Παρασκευή 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

    Τετάρτη 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.