DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Patch Management in the Age of IoT: Challenges and Solutions
  • XZ Utils Backdoor [Comic]
  • How To Implement a Patch Management Process
  • Patch Management and Container Security

Trending

  • Microsoft Azure Synapse Analytics: Scaling Hurdles and Limitations
  • Scaling InfluxDB for High-Volume Reporting With Continuous Queries (CQs)
  • Optimize Deployment Pipelines for Speed, Security and Seamless Automation
  • Scaling in Practice: Caching and Rate-Limiting With Redis and Next.js
  1. DZone
  2. Software Design and Architecture
  3. Security
  4. Getting Started with Patch Endpoint

Getting Started with Patch Endpoint

Getting started with patch endpoint with JSON Merge Patch Message converter. Let's start and test the same in Postman.

By 
Vicky Singh user avatar
Vicky Singh
·
Jun. 30, 20 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
9.8K Views

Join the DZone community and get the full member experience.

Join For Free

Let's assert into a quick tutorial covering sending a PATCH request to a Rest Controller in Spring Boot.

If you're starting from scratch, then you might want to have a look at Spring’s starter guide. The setup is covered in the link provided.

The maven dependencies we need to add:

XML
 




x


 
1
<dependencies>
2
  <dependency>
3
      <groupId>org.springframework.boot</groupId>
4
      <artifactId>spring-boot-starter-web</artifactId>
5
  </dependency>
6
  <dependency>
7
      <groupId>org.springframework.boot</groupId>
8
      <artifactId>spring-boot-starter-test</artifactId>
9
      <scope>test</scope>
10
  </dependency>
11
  <dependency>
12
      <groupId>javax.json</groupId>
13
      <artifactId>javax.json-api</artifactId>
14
      <version>1.1.4</version>
15
  </dependency>
16
  <dependency>
17
        <groupId>com.fasterxml.jackson.datatype</groupId>
18
        <artifactId>jackson-datatype-jsr353</artifactId>
19
        <version>2.9.8</version>
20
   </dependency>
21
   <dependency>
22
      <groupId>org.apache.johnzon</groupId>
23
      <artifactId>johnzon-core</artifactId>
24
  </dependency>
25
</dependencies>


Previously, placing our leg into the Patch endpoint, let's view having the contrast among patch and put.

The patch is utilized when you need to apply a halfway update to the resource. Let's expect a school that has the following highlights.

JSON
 




xxxxxxxxxx
1


 
1
{
2
 "front_patio": true,
3
 "back_patio": true,
4
 "windows": 12,
5
 "doors": 4,
6
 "Balcony": false
7
}


What's more, we need to make the accompanying update:

JSON
 




xxxxxxxxxx
1


 
1
{
2
 "doors": 5
3
}


The outcome will be the following:

JSON
 




xxxxxxxxxx
1


 
1
{
2
"front_patio": true,
3
"back_patio": true,
4
"windows": 12,
5
"doors": 5,
6
"Balcony": false
7
}



To parse a PATCH demand payload, we should take an approaching solicitation with the application/blend patch+json content sort, the payload must be changed over to an occurrence of JsonMergePatch. 

Spring MVC, be that as it may, doesn't have the foggiest idea how to make examples of JsonMergePatch. So we have to give a custom HttpMessageConverter<T> to each sort. Luckily it's quite direct. For accommodation, how about we broaden AbstractHttpMessageConverter<T> and annotate on the execution with @Component, so Spring can get it 

Here the constructor will conjure the parent's constructor demonstrating the upheld media type for this converter, We additionally demonstrate that our converter underpins the mergePatch class

Java
 




x



1
import org.springframework.http.HttpInputMessage;
2
import org.springframework.http.HttpOutputMessage;
3
import org.springframework.http.MediaType;
4
import org.springframework.http.converter.AbstractHttpMessageConverter;
5
import org.springframework.http.converter.HttpMessageNotReadableException;
6
import org.springframework.http.converter.HttpMessageNotWritableException;
7
import org.springframework.stereotype.Component;
8

          
9
import javax.json.Json;
10
import javax.json.JsonMergePatch;
11
import javax.json.JsonReader;
12
import javax.json.JsonWriter;
13

          
14
@Component
15
public class JsonMergePatchHttpMessageConverter extends AbstractHttpMessageConverter<JsonMergePatch> {
16

          
17
    public JsonMergePatchHttpMessageConverter() {
18
        super(MediaType.valueOf("application/merge-patch+json"));
19
    }
20

          
21
    @Override
22
    protected boolean supports(Class<?> clazz) {
23
        return JsonMergePatch.class.isAssignableFrom(clazz);
24
    }
25

          
26
    @Override
27
    protected JsonMergePatch readInternal(Class<? extends JsonMergePatch> clazz, HttpInputMessage inputMessage)
28
            throws HttpMessageNotReadableException {
29

          
30
        try (JsonReader reader = Json.createReader(inputMessage.getBody())) {
31
            return Json.createMergePatch(reader.readValue());
32
        } catch (Exception e) {
33
            return null;
34
        }
35
    }
36

          
37
    @Override
38
    protected void writeInternal(JsonMergePatch jsonMergePatch, HttpOutputMessage outputMessage)
39
            throws HttpMessageNotWritableException {
40

          
41
        try (JsonWriter writer = Json.createWriter(outputMessage.getBody())) {
42
            writer.write(jsonMergePatch.toJsonValue());
43
        } catch (Exception e) {
44
            throw new HttpMessageNotWritableException(e.getMessage(), e);
45
        }
46
    }
47
}
48

          


and add the converter to configuration.

Java
 




xxxxxxxxxx
1


 
1
@Configuration
2
public class ...... extends WebMvcConfigurationSupport {
3
  ........
4
@Override
5
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
6
        converters.add(jsonMergePatchHttpMessageConverter);
7
        addDefaultHttpMessageConverters(converters);
8
}
9
}


Here's the Rest controller for School Example

Java
 




x


 
1
@RestController
2
public class SchoolController {
3
    @Autowired private SchoolService schoolService;
4
    
5
    @PatchMapping(path = "/school/{schoolId}", consumes = "application/merge-patch+json")
6
    public ResponseEntity <Void> patchSchool(
7
             @PathVariable Long schoolId,
8
             @RequestBody JsonMergePatch patchRequest) {
9
        Void result = schoolService.patchSchool(schoolId, patchRequest);
10
        return new ResponseEntity<>(result, HttpStatus.OK);
11
    }
12
}


We have to get the underlying school from backend, and fixed the passed patchRequest and spare the current example. here for blending the pacthed information, we need to make a Patch Helper for it.

Java
 




xxxxxxxxxx
1
42


 
1
@Component
2
public class PatchHelper {
3

          
4
    private final ObjectMapper mapper;
5
    private final Validator validator;
6

          
7
    public PatchHelper(Validator validator) {
8
        this.validator = validator;
9
        this.mapper = new ObjectMapper()
10
                .setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL)
11
                .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
12
                .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
13
                .findAndRegisterModules()
14
                .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
15
    }
16

          
17
    public <T> T mergePatch(JsonMergePatch mergePatch, T targetBean, Class<T> beanClass) {
18
        JsonValue target = mapper.convertValue(targetBean, JsonValue.class);
19
        JsonValue patched = applyMergePatch(mergePatch, target);
20
        return convertAndValidate(patched, beanClass);
21
    }
22

          
23
    private JsonValue applyMergePatch(JsonMergePatch mergePatch, JsonValue target) {
24
        try {
25
            return mergePatch.apply(target);
26
        } catch (Exception e) {
27
            throw new RuntimeException(e);
28
        }
29
    }
30

          
31
    private <T> T convertAndValidate(JsonValue jsonValue, Class<T> beanClass) {
32
        T bean = mapper.convertValue(jsonValue, beanClass);
33
        validate(bean);
34
        return bean;
35
    }
36

          
37
    private <T> void validate(T bean) {
38
        Set<ConstraintViolation<T>> violations = validator.validate(bean);
39
        if (!violations.isEmpty()) {
40
            throw new ConstraintViolationException(violations);
41
        }
42
    }


We are done, now we can directly use this patch helper to patch the passed request.

Java
 




x


 
1
School initialschool = new School(true, true, 12, 4, false);
2
School patchedSchool = patchHelper.mergePatch(patchRequest, initialschool,
3
                    School.class);
4
System.out.print(initialschool);


Summary: JSON Merge Patch is an innocently straightforward arrangement, with restricted ease of use. Likely it is a decent decision in the event that you are building something little, with straightforward JSON Schema, however, you need to offer a rapidly reasonable, pretty much-working strategy for customers to refresh JSON records. A REST API intended for open utilization however without fitting customer libraries may be a genuine model.

patchRequest example {"doors":5}

You may discover the source code of these examples here:: https://bitbucket.org/git-test1787/simple-patch-endpoint/src 

Patch (computing)

Opinions expressed by DZone contributors are their own.

Related

  • Patch Management in the Age of IoT: Challenges and Solutions
  • XZ Utils Backdoor [Comic]
  • How To Implement a Patch Management Process
  • Patch Management and Container Security

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!