kandi background
Explore Kits

lombok | Very spicy additions to the Java programming language.

 by   rzwitserloot Java Version: v1.18.16 License: Non-SPDX

 by   rzwitserloot Java Version: v1.18.16 License: Non-SPDX

Download this library from

kandi X-RAY | lombok Summary

lombok is a Java library. lombok has no bugs, it has no vulnerabilities and it has medium support. However lombok build file is not available and it has a Non-SPDX License. You can download it from GitHub, Maven.
Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java. Never write another getter or equals method again, with one annotation your class has a fully featured builder, automate your logging variables, and much more. See LICENSE for the Project Lombok license.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • lombok has a medium active ecosystem.
  • It has 10170 star(s) with 1932 fork(s). There are 412 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 657 open issues and 1801 have been closed. On average issues are closed in 199 days. There are 9 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of lombok is v1.18.16
lombok Support
Best in #Java
Average in #Java
lombok Support
Best in #Java
Average in #Java

quality kandi Quality

  • lombok has 0 bugs and 0 code smells.
lombok Quality
Best in #Java
Average in #Java
lombok Quality
Best in #Java
Average in #Java

securitySecurity

  • lombok has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • lombok code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
lombok Security
Best in #Java
Average in #Java
lombok Security
Best in #Java
Average in #Java

license License

  • lombok has a Non-SPDX License.
  • Non-SPDX licenses can be open source with a non SPDX compliant license, or non open source licenses, and you need to review them closely before use.
lombok License
Best in #Java
Average in #Java
lombok License
Best in #Java
Average in #Java

buildReuse

  • lombok releases are available to install and integrate.
  • Deployable package is available in Maven.
  • lombok has no build file. You will be need to create the build yourself to build the component from source.
  • It has 91049 lines of code, 8182 functions and 1523 files.
  • It has medium code complexity. Code complexity directly impacts maintainability of the code.
lombok Reuse
Best in #Java
Average in #Java
lombok Reuse
Best in #Java
Average in #Java
Top functions reviewed by kandi - BETA

Coming Soon for all Libraries!

Currently covering the most popular Java, JavaScript and Python libraries. See a SAMPLE HERE.
kandi's functional review helps you automatically verify the functionalities of the libraries and avoid rework.

lombok Key Features

Very spicy additions to the Java programming language.

Eclipse not able to open java files -> Unable to make protected final java.lang.Class java.lang.ClassLoader.defineClass

copy iconCopydownload iconDownload
--illegal-access=warn
--add-opens java.base/java.lang=ALL-UNNAMED
-----------------------
-javaagent:C:\<location>\eclipse-jee-2022-03-R-win32-x86_64\lombok.jar

Lombok's @Builder not detecting fields of the Java Record

copy iconCopydownload iconDownload
@Builder
public record MyRecord(String myField) {}
public record MyRecord(String myField) {
    @Builder public MyRecord {}
} 
-----------------------
@Builder
public record MyRecord(String myField) {}
public record MyRecord(String myField) {
    @Builder public MyRecord {}
} 

How to join custom queries spring boot

copy iconCopydownload iconDownload
@Data
public class StateCityCensusDto {

    private StateCensus stateCensus;
    private List<CityCensus> cities;

}
    Integer getCode();
    String getName();
    Long getCityPopulation();
    //add stateId retrieve from query
    Long getStateId();
}


      List<CensusStateStats> stateCensusList = //retrieve from the db;
      List<CensusStateCitiesStats>  //retrieve from the db;
      List<StateCityCensusDto> stateCityCensusList = new ArrayList<>();

    stateCensusList.forEach(stateCensus -> {
         StateCityCensusDto stateCityCensus = new StateCityCensusDto();
         stateCityCensus.setStateCensus(stateCensus);
         stateCityCensus.setCities(cityCensusList.stream()
                  .filter(c -> c.getStateId() == stateCensus.getId())
                  .collect(Collectors.toList()));
                   
        stateCityCensusList.add(stateCityCensus);
    });


-----------------------
@Data
public class StateCityCensusDto {

    private StateCensus stateCensus;
    private List<CityCensus> cities;

}
    Integer getCode();
    String getName();
    Long getCityPopulation();
    //add stateId retrieve from query
    Long getStateId();
}


      List<CensusStateStats> stateCensusList = //retrieve from the db;
      List<CensusStateCitiesStats>  //retrieve from the db;
      List<StateCityCensusDto> stateCityCensusList = new ArrayList<>();

    stateCensusList.forEach(stateCensus -> {
         StateCityCensusDto stateCityCensus = new StateCityCensusDto();
         stateCityCensus.setStateCensus(stateCensus);
         stateCityCensus.setCities(cityCensusList.stream()
                  .filter(c -> c.getStateId() == stateCensus.getId())
                  .collect(Collectors.toList()));
                   
        stateCityCensusList.add(stateCityCensus);
    });


-----------------------
@Data
public class StateCityCensusDto {

    private StateCensus stateCensus;
    private List<CityCensus> cities;

}
    Integer getCode();
    String getName();
    Long getCityPopulation();
    //add stateId retrieve from query
    Long getStateId();
}


      List<CensusStateStats> stateCensusList = //retrieve from the db;
      List<CensusStateCitiesStats>  //retrieve from the db;
      List<StateCityCensusDto> stateCityCensusList = new ArrayList<>();

    stateCensusList.forEach(stateCensus -> {
         StateCityCensusDto stateCityCensus = new StateCityCensusDto();
         stateCityCensus.setStateCensus(stateCensus);
         stateCityCensus.setCities(cityCensusList.stream()
                  .filter(c -> c.getStateId() == stateCensus.getId())
                  .collect(Collectors.toList()));
                   
        stateCityCensusList.add(stateCityCensus);
    });


How to ignore 1 field in Java equals() for custom object?

copy iconCopydownload iconDownload
@EqualsAndHashCode
public class MyObject{

    @EqualsAndHashCode.Exclude
    Object fieldToExclude;

}
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class MyObject{

    @EqualsAndHashCode.Include
    Object fieldToInclude;

}
-----------------------
@EqualsAndHashCode
public class MyObject{

    @EqualsAndHashCode.Exclude
    Object fieldToExclude;

}
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class MyObject{

    @EqualsAndHashCode.Include
    Object fieldToInclude;

}

Spring Batch cannot Load the JobBuilderFactory in my integration test

copy iconCopydownload iconDownload
import org.springframework.batch.test.JobLauncherTestUtils
import org.springframework.batch.test.JobRepositoryTestUtils
import org.springframework.context.annotation.Bean

class JobSpecConfiguration {
    @Bean
    JobLauncherTestUtils getJobLauncherTestUtils() {
        new JobLauncherTestUtils()
    }

    @Bean
    JobRepositoryTestUtils getJobRepositoryTestUtils() {
        new JobRepositoryTestUtils()
    }
}
import org.spockframework.spring.SpringBean
import org.springframework.batch.core.Job
import org.springframework.batch.test.JobLauncherTestUtils
import org.springframework.batch.test.JobRepositoryTestUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.boot.test.context.TestConfiguration
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Primary
import org.springframework.test.annotation.DirtiesContext
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.context.ContextConfiguration
import spock.lang.Specification

@DirtiesContext
@ContextConfiguration(classes = [Application, TestConfig])
@ActiveProfiles(['test', 'kafka'])
class SubmitFilesJobSpec extends Specification {

    @Autowired
    private JobLauncherTestUtils jobLauncherTestUtils

    @Autowired
    private JobRepositoryTestUtils jobRepositoryTestUtils

    @SpringBean
    private SomeRepo someRepo = Mock()

    def cleanup() {
        jobRepositoryTestUtils.removeJobExecutions()
    }

    //some unit test that we have
    def "Verify batch run"() {
        given: "At least 1 Open Record"
        def record = defaultData()
        someRepo.findTop1ByStatus(_) >> record

        when: "A batch job has been triggered"
        def jobExecution = jobLauncherTestUtils.launchJob(BaseJobExecution.getJobParameters(null))

        then: "Job will be completed with at least 1 persisted/processed record"
        2 == jobExecution.getStepExecutions().size()
        jobExecution.getStepExecutions().forEach(stepExecution -> {
            1 == stepExecution.getWriteCount()
        })
        "SOME_JOB_NAME" == jobExecution.getJobInstance().getJobName()
        "COMPLETED" == jobExecution.getExitStatus().getExitCode()
    }

    @TestConfiguration
    static class TestConfig extends JobSpecConfiguration {

        @Override
        @Bean
        JobLauncherTestUtils getJobLauncherTestUtils() {
            new JobLauncherTestUtils() {
                @Override
                @Autowired
                void setJob(@Qualifier("submitFilesJob") Job job) {
                    super.setJob(job)
                }
            }
        }
    }

-----------------------
import org.springframework.batch.test.JobLauncherTestUtils
import org.springframework.batch.test.JobRepositoryTestUtils
import org.springframework.context.annotation.Bean

class JobSpecConfiguration {
    @Bean
    JobLauncherTestUtils getJobLauncherTestUtils() {
        new JobLauncherTestUtils()
    }

    @Bean
    JobRepositoryTestUtils getJobRepositoryTestUtils() {
        new JobRepositoryTestUtils()
    }
}
import org.spockframework.spring.SpringBean
import org.springframework.batch.core.Job
import org.springframework.batch.test.JobLauncherTestUtils
import org.springframework.batch.test.JobRepositoryTestUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.boot.test.context.TestConfiguration
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Primary
import org.springframework.test.annotation.DirtiesContext
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.context.ContextConfiguration
import spock.lang.Specification

@DirtiesContext
@ContextConfiguration(classes = [Application, TestConfig])
@ActiveProfiles(['test', 'kafka'])
class SubmitFilesJobSpec extends Specification {

    @Autowired
    private JobLauncherTestUtils jobLauncherTestUtils

    @Autowired
    private JobRepositoryTestUtils jobRepositoryTestUtils

    @SpringBean
    private SomeRepo someRepo = Mock()

    def cleanup() {
        jobRepositoryTestUtils.removeJobExecutions()
    }

    //some unit test that we have
    def "Verify batch run"() {
        given: "At least 1 Open Record"
        def record = defaultData()
        someRepo.findTop1ByStatus(_) >> record

        when: "A batch job has been triggered"
        def jobExecution = jobLauncherTestUtils.launchJob(BaseJobExecution.getJobParameters(null))

        then: "Job will be completed with at least 1 persisted/processed record"
        2 == jobExecution.getStepExecutions().size()
        jobExecution.getStepExecutions().forEach(stepExecution -> {
            1 == stepExecution.getWriteCount()
        })
        "SOME_JOB_NAME" == jobExecution.getJobInstance().getJobName()
        "COMPLETED" == jobExecution.getExitStatus().getExitCode()
    }

    @TestConfiguration
    static class TestConfig extends JobSpecConfiguration {

        @Override
        @Bean
        JobLauncherTestUtils getJobLauncherTestUtils() {
            new JobLauncherTestUtils() {
                @Override
                @Autowired
                void setJob(@Qualifier("submitFilesJob") Job job) {
                    super.setJob(job)
                }
            }
        }
    }

Unsatisfied dependency exception for bean type java.util.Properties

copy iconCopydownload iconDownload
@Bean
public FactoryBean<Properties> employeeQueries() throws IOException {
    final var factory = new PropertiesFactoryBean();
    // please prefer: File- ressource with *absolute* path, alternatively (spring) Classpath- or ServletContext-
    factory.setLocation(new FileSystemResource("database/employee-queries.properties"));
    return factory;
}
factory.afterProertiesSet();
factory.getObject();
(any spring)InitializingBean factory = new InitializingBean();
factory.setXXX(...)
factory.setYYY(...)
factory.afterProertiesSet();
factory.getObject();
-----------------------
@Bean
public FactoryBean<Properties> employeeQueries() throws IOException {
    final var factory = new PropertiesFactoryBean();
    // please prefer: File- ressource with *absolute* path, alternatively (spring) Classpath- or ServletContext-
    factory.setLocation(new FileSystemResource("database/employee-queries.properties"));
    return factory;
}
factory.afterProertiesSet();
factory.getObject();
(any spring)InitializingBean factory = new InitializingBean();
factory.setXXX(...)
factory.setYYY(...)
factory.afterProertiesSet();
factory.getObject();
-----------------------
@Bean
public FactoryBean<Properties> employeeQueries() throws IOException {
    final var factory = new PropertiesFactoryBean();
    // please prefer: File- ressource with *absolute* path, alternatively (spring) Classpath- or ServletContext-
    factory.setLocation(new FileSystemResource("database/employee-queries.properties"));
    return factory;
}
factory.afterProertiesSet();
factory.getObject();
(any spring)InitializingBean factory = new InitializingBean();
factory.setXXX(...)
factory.setYYY(...)
factory.afterProertiesSet();
factory.getObject();
-----------------------
@Bean
public FactoryBean<Properties> employeeQueries() throws IOException {
    final var factory = new PropertiesFactoryBean();
    // please prefer: File- ressource with *absolute* path, alternatively (spring) Classpath- or ServletContext-
    factory.setLocation(new FileSystemResource("database/employee-queries.properties"));
    return factory;
}
factory.afterProertiesSet();
factory.getObject();
(any spring)InitializingBean factory = new InitializingBean();
factory.setXXX(...)
factory.setYYY(...)
factory.afterProertiesSet();
factory.getObject();
-----------------------
@Bean
public FactoryBean<Properties> employeeQueries() throws IOException {
    final var factory = new PropertiesFactoryBean();
    // please prefer: File- ressource with *absolute* path, alternatively (spring) Classpath- or ServletContext-
    factory.setLocation(new FileSystemResource("database/employee-queries.properties"));
    return factory;
}
factory.afterProertiesSet();
factory.getObject();
(any spring)InitializingBean factory = new InitializingBean();
factory.setXXX(...)
factory.setYYY(...)
factory.afterProertiesSet();
factory.getObject();
-----------------------
@Bean
public FactoryBean<Properties> employeeQueries() throws IOException {
    final var factory = new PropertiesFactoryBean();
    // please prefer: File- ressource with *absolute* path, alternatively (spring) Classpath- or ServletContext-
    factory.setLocation(new FileSystemResource("database/employee-queries.properties"));
    return factory;
}
factory.afterProertiesSet();
factory.getObject();
(any spring)InitializingBean factory = new InitializingBean();
factory.setXXX(...)
factory.setYYY(...)
factory.afterProertiesSet();
factory.getObject();

How to create a builder for third party POJO?

copy iconCopydownload iconDownload
public class ThirdPartyPojoBuilder extends ThirdPartyPojo {
    @Builder
    public ThirdPartyPojoBuilder(String name) {
        this.setName(name);
    }
}
var thirdPartyPojo = ThirdPartyPojoBuilder.builder().name("A Name").build();
-----------------------
public class ThirdPartyPojoBuilder extends ThirdPartyPojo {
    @Builder
    public ThirdPartyPojoBuilder(String name) {
        this.setName(name);
    }
}
var thirdPartyPojo = ThirdPartyPojoBuilder.builder().name("A Name").build();
-----------------------

@Builder
public class ThirdPartyPojoBuilder extends ThirdPartyPojo {
    @Default
    private String name = "default name" 

    public ThirdPartyPojoBuilder(String name) {
        this.setName(name);
    }
}
ThirdPartyPojo pojoWithDefaultName = ThirdPartyPojoBuilder.builder().build();
ThirdPartyPojo pojoWithCustomName = ThirdPartyPojoBuilder.builder().name("custom name").build();

System.out.println(pojoWithDefaultName.getName()); // prints "default name"
System.out.println(pojoWithCustomName.getName());  // prints "custom name"
-----------------------

@Builder
public class ThirdPartyPojoBuilder extends ThirdPartyPojo {
    @Default
    private String name = "default name" 

    public ThirdPartyPojoBuilder(String name) {
        this.setName(name);
    }
}
ThirdPartyPojo pojoWithDefaultName = ThirdPartyPojoBuilder.builder().build();
ThirdPartyPojo pojoWithCustomName = ThirdPartyPojoBuilder.builder().name("custom name").build();

System.out.println(pojoWithDefaultName.getName()); // prints "default name"
System.out.println(pojoWithCustomName.getName());  // prints "custom name"

default Jackson naming strategy for fields with short names

copy iconCopydownload iconDownload
@Builder
@Jacksonized
class ComputationResult {

    private final String pId;
    private final String cId;

    @JsonProperty("pId")
    public String getPId() {
        return pId;
    }

    @JsonProperty("cId")
    public String getCId() {
        return cId;
    }
}

Why my java lambda expression cannot work while its imperative style works properly?

copy iconCopydownload iconDownload
public class AAA implements Serializable {

    @FunctionalInterface
    public interface ForeachFunction<T> extends Serializable {
        void call(T t) throws Exception;
    }

    @Test
    public void testBlock1() throws FileNotFoundException, IOException {
        ForeachFunction<String> functionBody = new ForeachFunction<String>() {
            public void call(String t) throws Exception {
                System.out.println(t);
            }
        };
        try (FileOutputStream fos = new FileOutputStream("data/block1.obj");
            ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(functionBody);  // success
        }
    }

    @Test
    public void testBlock2() throws FileNotFoundException, IOException {
        ForeachFunction<String> functionBody = System.out::println;
        try (FileOutputStream fos = new FileOutputStream("data/block2.obj");
            ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(functionBody);  // fail (NotSerializableException)
        }
    }
}

How to print complete error message when logging an exception generated by RestTemplate?

copy iconCopydownload iconDownload
@Test
void shouldPrintErrorForRestTemplate() {
    try {

        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getForEntity("http://hellosmilep.free.beeceptor.com/error/notfound", String.class);

    } catch(HttpClientErrorException e) {
        log.error(e.getResponseBodyAsString(),e);
    }catch (Exception e) {
        log.error("Error calling REST API", e);
    }
}
-----------------------
/**
  * Return error message with details from the response body, possibly truncated:
  * <pre>
  * 404 Not Found: [{'id': 123, 'message': 'my very long... (500 bytes)]
  * </pre>
  */
private String getErrorMessage(
    int rawStatusCode, String statusText, @Nullable byte[] responseBody, @Nullable Charset charset) {


  String preface = rawStatusCode + " " + statusText + ": ";
  if (ObjectUtils.isEmpty(responseBody)) {
    return preface + "[no body]";
  }


  if (charset == null) {
    charset = StandardCharsets.UTF_8;
  }
  int maxChars = 200;


  if (responseBody.length < maxChars * 2) {
    return preface + "[" + new String(responseBody, charset) + "]";
  }


  try {
    Reader reader = new InputStreamReader(new ByteArrayInputStream(responseBody), charset);
    CharBuffer buffer = CharBuffer.allocate(maxChars);
    reader.read(buffer);
    reader.close();
    buffer.flip();
    return preface + "[" + buffer.toString() + "... (" + responseBody.length + " bytes)]";
  }
  catch (IOException ex) {
    // should never happen
    throw new IllegalStateException(ex);
  }
}
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.UnknownHttpStatusCodeException;

public class CustomRestTemplateResponseErrorHandler extends DefaultResponseErrorHandler {
  
  // This overloaded method version is only available since Spring 5.0
  // For previous versions of the library you can override
  // handleError(ClientHttpResponse response) instead
  @Override
  protected void handleError(ClientHttpResponse response, HttpStatus statusCode) throws IOException {
    String statusText = response.getStatusText();
    HttpHeaders headers = response.getHeaders();
    byte[] body = getResponseBody(response);
    Charset charset = getCharset(response);
    String message = getErrorMessage(statusCode.value(), statusText, body, charset);

    switch (statusCode.series()) {
      case CLIENT_ERROR:
        throw HttpClientErrorException.create(message, statusCode, statusText, headers, body, charset);
      case SERVER_ERROR:
        throw HttpServerErrorException.create(message, statusCode, statusText, headers, body, charset);
      default:
        throw new UnknownHttpStatusCodeException(message, statusCode.value(), statusText, headers, body, charset);
    }
  }

  /**
   * Return error message with details from the response body:
   * <pre>
   * 404 Not Found: [{'id': 123, 'message': 'actual mesage']
   * </pre>
   *
   * In contrast to <code>DefaultResponseErrorHandler</code>, the message will not be truncated.
   */
  private String getErrorMessage(
      int rawStatusCode, String statusText, @Nullable byte[] responseBody, @Nullable Charset charset) {

    String preface = rawStatusCode + " " + statusText + ": ";
    if (ObjectUtils.isEmpty(responseBody)) {
      return preface + "[no body]";
    }

    if (charset == null) {
      charset = StandardCharsets.UTF_8;
    }

    // return the message without truncation
    return preface + "[" + new String(responseBody, charset) + "]";
  }
}
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

@Slf4j
public class RestTemplateTest {

    @Test
    void shouldPrintErrorForRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        ResponseErrorHandler errorHandler = new CustomRestTemplateResponseErrorHandler();
        restTemplate.setErrorHandler(errorHandler);

        try {
            restTemplate.getForEntity("http://hellosmilep.free.beeceptor.com/error/notfound", String.class);
        } catch (Exception e) {
            log.error("Error calling REST API", e);
        }
    }
}
-----------------------
/**
  * Return error message with details from the response body, possibly truncated:
  * <pre>
  * 404 Not Found: [{'id': 123, 'message': 'my very long... (500 bytes)]
  * </pre>
  */
private String getErrorMessage(
    int rawStatusCode, String statusText, @Nullable byte[] responseBody, @Nullable Charset charset) {


  String preface = rawStatusCode + " " + statusText + ": ";
  if (ObjectUtils.isEmpty(responseBody)) {
    return preface + "[no body]";
  }


  if (charset == null) {
    charset = StandardCharsets.UTF_8;
  }
  int maxChars = 200;


  if (responseBody.length < maxChars * 2) {
    return preface + "[" + new String(responseBody, charset) + "]";
  }


  try {
    Reader reader = new InputStreamReader(new ByteArrayInputStream(responseBody), charset);
    CharBuffer buffer = CharBuffer.allocate(maxChars);
    reader.read(buffer);
    reader.close();
    buffer.flip();
    return preface + "[" + buffer.toString() + "... (" + responseBody.length + " bytes)]";
  }
  catch (IOException ex) {
    // should never happen
    throw new IllegalStateException(ex);
  }
}
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.UnknownHttpStatusCodeException;

public class CustomRestTemplateResponseErrorHandler extends DefaultResponseErrorHandler {
  
  // This overloaded method version is only available since Spring 5.0
  // For previous versions of the library you can override
  // handleError(ClientHttpResponse response) instead
  @Override
  protected void handleError(ClientHttpResponse response, HttpStatus statusCode) throws IOException {
    String statusText = response.getStatusText();
    HttpHeaders headers = response.getHeaders();
    byte[] body = getResponseBody(response);
    Charset charset = getCharset(response);
    String message = getErrorMessage(statusCode.value(), statusText, body, charset);

    switch (statusCode.series()) {
      case CLIENT_ERROR:
        throw HttpClientErrorException.create(message, statusCode, statusText, headers, body, charset);
      case SERVER_ERROR:
        throw HttpServerErrorException.create(message, statusCode, statusText, headers, body, charset);
      default:
        throw new UnknownHttpStatusCodeException(message, statusCode.value(), statusText, headers, body, charset);
    }
  }

  /**
   * Return error message with details from the response body:
   * <pre>
   * 404 Not Found: [{'id': 123, 'message': 'actual mesage']
   * </pre>
   *
   * In contrast to <code>DefaultResponseErrorHandler</code>, the message will not be truncated.
   */
  private String getErrorMessage(
      int rawStatusCode, String statusText, @Nullable byte[] responseBody, @Nullable Charset charset) {

    String preface = rawStatusCode + " " + statusText + ": ";
    if (ObjectUtils.isEmpty(responseBody)) {
      return preface + "[no body]";
    }

    if (charset == null) {
      charset = StandardCharsets.UTF_8;
    }

    // return the message without truncation
    return preface + "[" + new String(responseBody, charset) + "]";
  }
}
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

@Slf4j
public class RestTemplateTest {

    @Test
    void shouldPrintErrorForRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        ResponseErrorHandler errorHandler = new CustomRestTemplateResponseErrorHandler();
        restTemplate.setErrorHandler(errorHandler);

        try {
            restTemplate.getForEntity("http://hellosmilep.free.beeceptor.com/error/notfound", String.class);
        } catch (Exception e) {
            log.error("Error calling REST API", e);
        }
    }
}
-----------------------
/**
  * Return error message with details from the response body, possibly truncated:
  * <pre>
  * 404 Not Found: [{'id': 123, 'message': 'my very long... (500 bytes)]
  * </pre>
  */
private String getErrorMessage(
    int rawStatusCode, String statusText, @Nullable byte[] responseBody, @Nullable Charset charset) {


  String preface = rawStatusCode + " " + statusText + ": ";
  if (ObjectUtils.isEmpty(responseBody)) {
    return preface + "[no body]";
  }


  if (charset == null) {
    charset = StandardCharsets.UTF_8;
  }
  int maxChars = 200;


  if (responseBody.length < maxChars * 2) {
    return preface + "[" + new String(responseBody, charset) + "]";
  }


  try {
    Reader reader = new InputStreamReader(new ByteArrayInputStream(responseBody), charset);
    CharBuffer buffer = CharBuffer.allocate(maxChars);
    reader.read(buffer);
    reader.close();
    buffer.flip();
    return preface + "[" + buffer.toString() + "... (" + responseBody.length + " bytes)]";
  }
  catch (IOException ex) {
    // should never happen
    throw new IllegalStateException(ex);
  }
}
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.UnknownHttpStatusCodeException;

public class CustomRestTemplateResponseErrorHandler extends DefaultResponseErrorHandler {
  
  // This overloaded method version is only available since Spring 5.0
  // For previous versions of the library you can override
  // handleError(ClientHttpResponse response) instead
  @Override
  protected void handleError(ClientHttpResponse response, HttpStatus statusCode) throws IOException {
    String statusText = response.getStatusText();
    HttpHeaders headers = response.getHeaders();
    byte[] body = getResponseBody(response);
    Charset charset = getCharset(response);
    String message = getErrorMessage(statusCode.value(), statusText, body, charset);

    switch (statusCode.series()) {
      case CLIENT_ERROR:
        throw HttpClientErrorException.create(message, statusCode, statusText, headers, body, charset);
      case SERVER_ERROR:
        throw HttpServerErrorException.create(message, statusCode, statusText, headers, body, charset);
      default:
        throw new UnknownHttpStatusCodeException(message, statusCode.value(), statusText, headers, body, charset);
    }
  }

  /**
   * Return error message with details from the response body:
   * <pre>
   * 404 Not Found: [{'id': 123, 'message': 'actual mesage']
   * </pre>
   *
   * In contrast to <code>DefaultResponseErrorHandler</code>, the message will not be truncated.
   */
  private String getErrorMessage(
      int rawStatusCode, String statusText, @Nullable byte[] responseBody, @Nullable Charset charset) {

    String preface = rawStatusCode + " " + statusText + ": ";
    if (ObjectUtils.isEmpty(responseBody)) {
      return preface + "[no body]";
    }

    if (charset == null) {
      charset = StandardCharsets.UTF_8;
    }

    // return the message without truncation
    return preface + "[" + new String(responseBody, charset) + "]";
  }
}
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

@Slf4j
public class RestTemplateTest {

    @Test
    void shouldPrintErrorForRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        ResponseErrorHandler errorHandler = new CustomRestTemplateResponseErrorHandler();
        restTemplate.setErrorHandler(errorHandler);

        try {
            restTemplate.getForEntity("http://hellosmilep.free.beeceptor.com/error/notfound", String.class);
        } catch (Exception e) {
            log.error("Error calling REST API", e);
        }
    }
}

Community Discussions

Trending Discussions on lombok
  • Eclipse not able to open java files -&gt; Unable to make protected final java.lang.Class java.lang.ClassLoader.defineClass
  • Maven: Can I use a version from dependency management in annotationProcessorPath?
  • Java, Intellij IDEA problem Unrecognized option: --add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED
  • How to Vaadin CallbackDataProvider make an asyncronous fetch data?
  • Cannot find Lombok plugin in Android Studio 2021.1.1 (build of 2022)
  • Lombok Plugin Does not Working In Latest Version Of Android Studio (Bumblebee)
  • Lombok @SuperBuilder on abstract class with generic cause error: incompatible types
  • Java 17: Maven doesn't give much information about the error that happened, why?
  • Lombok's @Builder not detecting fields of the Java Record
  • Lombok and @Autowired
Trending Discussions on lombok

QUESTION

Eclipse not able to open java files -&gt; Unable to make protected final java.lang.Class java.lang.ClassLoader.defineClass

Asked 2022-Mar-28 at 17:31

Getting the following error, after adding Lombok lib

An error has occurred. See error log for more details.
Unable to make protected final java.lang.Class java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int) throws java.lang.ClassFormatError accessible: module java.base does not "opens java.lang" to unnamed module @1d1c37d5

ANSWER

Answered 2021-Sep-17 at 15:43

Add the below lines to the end of the eclipse.ini file

--illegal-access=warn
--add-opens java.base/java.lang=ALL-UNNAMED

Source https://stackoverflow.com/questions/69218106

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install lombok

You can download it from GitHub, Maven.
You can use lombok like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the lombok component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

Support

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Share this Page

share link
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.