kandi background
Explore Kits

spring-framework | Spring Framework : the foundation for all Spring | Model View Controller library

 by   spring-projects Java Version: v5.3.19 License: Apache-2.0

 by   spring-projects Java Version: v5.3.19 License: Apache-2.0

Download this library from

kandi X-RAY | spring-framework Summary

spring-framework is a Java library typically used in Architecture, Model View Controller, Spring Boot, Spring, Framework applications. spring-framework has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has medium support. You can download it from GitHub, Maven.
This is the home of the Spring Framework: the foundation for all Spring projects. Collectively the Spring Framework and the family of Spring projects are often referred to simply as "Spring". Spring provides everything required beyond the Java programming language for creating enterprise applications for a wide range of scenarios and architectures. Please read the Overview section as reference for a more complete introduction.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • spring-framework has a medium active ecosystem.
  • It has 47171 star(s) with 33374 fork(s). There are 3437 watchers for this library.
  • There were 10 major release(s) in the last 12 months.
  • There are 1131 open issues and 20723 have been closed. On average issues are closed in 82 days. There are 176 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of spring-framework is v5.3.19
spring-framework Support
Best in #Model View Controller
Average in #Model View Controller
spring-framework Support
Best in #Model View Controller
Average in #Model View Controller

quality kandi Quality

  • spring-framework has 0 bugs and 0 code smells.
spring-framework Quality
Best in #Model View Controller
Average in #Model View Controller
spring-framework Quality
Best in #Model View Controller
Average in #Model View Controller

securitySecurity

  • spring-framework has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • spring-framework code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
spring-framework Security
Best in #Model View Controller
Average in #Model View Controller
spring-framework Security
Best in #Model View Controller
Average in #Model View Controller

license License

  • spring-framework is licensed under the Apache-2.0 License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
spring-framework License
Best in #Model View Controller
Average in #Model View Controller
spring-framework License
Best in #Model View Controller
Average in #Model View Controller

buildReuse

  • spring-framework releases are available to install and integrate.
  • Deployable package is available in Maven.
  • Build file is available. You can build the component from source.
  • Installation instructions are available. Examples and code snippets are not available.
  • spring-framework saves you 1724864 person hours of effort in developing the same functionality from scratch.
  • It has 738235 lines of code, 76309 functions and 8366 files.
  • It has medium code complexity. Code complexity directly impacts maintainability of the code.
spring-framework Reuse
Best in #Model View Controller
Average in #Model View Controller
spring-framework Reuse
Best in #Model View Controller
Average in #Model View Controller
Top functions reviewed by kandi - BETA

kandi has reviewed spring-framework and discovered the below as its top functions. This is intended to give you an instant insight into spring-framework implemented functionality, and help decide if they suit your requirements.

  • Reads the bytecode instructions .
    • Deeply compare two objects .
      • Instantiates a bean using the factory method .
        • Puts this method information into the given byte vector .
          • Attempts to reconcile the declared parameters .
            • Emits the generated methods .
              • Generate code for comparison .
                • Determine the candidate constructors for the specified bean class .
                  • Invoke the given method .
                    • Attempt to match a pattern .

                      Get all kandi verified functions for this library.

                      Get all kandi verified functions for this library.

                      spring-framework Key Features

                      Spring Framework

                      StreamingResponseBody heap usage

                      copy iconCopydownload iconDownload
                       try (FileInputStream fis = new FileInputStream(fileName)) {
                           StreamUtils.copy(fis, dataOutputStream);
                       } catch (IOException e) {
                           log.error("Error writing file to stream",e);
                       }
                      
                      try (FileInputStream fis = new FileInputStream(fileName)) {
                          byte[] data = new byte[2048];
                          int read = 0;
                          while ((read = fis.read(data)) > 0) {
                              dataOutputStream.write(data, 0, read);
                          }
                          dataOutputStream.flush();
                      } catch (IOException e) {
                          log.error("Error writing file to stream",e);
                      }
                      
                       try (FileInputStream fis = new FileInputStream(fileName)) {
                           StreamUtils.copy(fis, dataOutputStream);
                       } catch (IOException e) {
                           log.error("Error writing file to stream",e);
                       }
                      
                      try (FileInputStream fis = new FileInputStream(fileName)) {
                          byte[] data = new byte[2048];
                          int read = 0;
                          while ((read = fis.read(data)) > 0) {
                              dataOutputStream.write(data, 0, read);
                          }
                          dataOutputStream.flush();
                      } catch (IOException e) {
                          log.error("Error writing file to stream",e);
                      }
                      
                        <dependency>
                              <groupId>org.zalando</groupId>
                              <artifactId>logbook-spring-boot-starter</artifactId>
                              <version>1.4.1</version>
                              <scope>compile</scope>
                        </dependency>
                      

                      Spring Boot 2.6 and Angular in static Resources

                      copy iconCopydownload iconDownload
                      const routes: Routes = [
                        {path: '', redirectTo: '/myProjects', pathMatch: 'full'},
                        //...
                        {path: '**', redirectTo: ''}
                      }
                      
                      @NgModule({
                        imports: [
                          RouterModule.forRoot(routes, {useHash: true})
                        ],
                        exports: [
                          RouterModule
                        ],
                        declarations: []
                      })
                      export class MyRoutingModule {
                      }
                      
                      @GetMapping("/{*path}")
                      
                      @Controller
                      class SpaRoutingController {
                      
                        @GetMapping("/{*path}")
                        fun forward(@PathVariable(value="path", required=false) path: String): String? {
                            if ("/".equals(path)) { // may need to handle additional cases
                               return ""; // or your index.html
                            }
                            return "forward:/";
                        }
                      }
                      
                      @GetMapping("/{*path}")
                      
                      @Controller
                      class SpaRoutingController {
                      
                        @GetMapping("/{*path}")
                        fun forward(@PathVariable(value="path", required=false) path: String): String? {
                            if ("/".equals(path)) { // may need to handle additional cases
                               return ""; // or your index.html
                            }
                            return "forward:/";
                        }
                      }
                      
                      <plugin>
                              <artifactId>maven-clean-plugin</artifactId>
                              <version>${maven-clean-plugin.version}</version>
                              <configuration>
                                <filesets>
                                  <fileset>
                                    <directory>src/main/webapp</directory>
                                    <includes>
                                      <include>*.js</include>
                                      <include>*.txt</include>
                                      <include>*.html</include>
                                      <include>*.css</include>
                                      <include>*.map</include>
                                      <include>*.json</include>
                                      <include>*.ico</include>
                                      <followSymlinks>false</followSymlinks>
                                    </includes>
                                  </fileset>
                                  <fileset>
                                    <directory>src/main/webapp/assets</directory>
                                    <includes>
                                      <include>**</include>
                                      <followSymlinks>false</followSymlinks>
                                    </includes>
                                  </fileset>
                                </filesets>
                              </configuration>
                              <executions>
                                <execution>
                                  <id>auto-clean</id>
                                  <phase>initialize</phase>
                                  <goals>
                                    <goal>clean</goal>
                                  </goals>
                                </execution>
                              </executions>
                            </plugin>
                      
                            <plugin>
                              <artifactId>maven-resources-plugin</artifactId>
                              <executions>
                                <execution>
                                  <id>copy-resources</id>
                                  <phase>process-resources</phase>
                                  <goals>
                                    <goal>copy-resources</goal>
                                  </goals>
                                  <configuration>
                                    <outputDirectory>${project.build.directory}/classes/static</outputDirectory>
                                    <includeEmptyDirs>true</includeEmptyDirs>
                                    <resources>
                                      <resource>
                                        <directory>${basedir}/src/main/${angular.project.name}/dist/${angular.project.name}</directory>
                                        <filtering>true</filtering>
                                      </resource>
                                    </resources>
                                  </configuration>
                                </execution>
                              </executions>
                            </plugin>
                      
                            <plugin>
                              <groupId>com.github.eirslett</groupId>
                              <artifactId>frontend-maven-plugin</artifactId>
                              <version>1.8.0</version>
                              <configuration>
                                <workingDirectory>src/main/${angular.project.name}</workingDirectory>
                              </configuration>
                              <executions>
                                <execution>
                                  <id>install node and npm</id>
                                  <goals>
                                    <goal>install-node-and-npm</goal>
                                  </goals>
                                  <phase>generate-resources</phase>
                                  <configuration>
                                    <nodeVersion>v14.16.1</nodeVersion>
                                  </configuration>
                      
                                </execution>
                                <execution>
                                  <id>npm build angular</id>
                                  <goals>
                                    <goal>npm</goal>
                                  </goals>
                                  <phase>generate-resources</phase>
                                  <configuration>
                                    <arguments>run build:prod</arguments>
                                  </configuration>
                                </execution>
                              </executions>
                            </plugin>
                      
                      @Configuration
                      public class ApplicationWebMvcConfiguration implements WebMvcConfigurer {
                        @Override
                        public void addResourceHandlers(ResourceHandlerRegistry registry) {
                      
                          registry.addResourceHandler("/**")
                                  .addResourceLocations("classpath:/static/")
                                  .resourceChain(true)
                                  .addResolver(new PathResourceResolver() {
                                    @Override
                                    protected Resource getResource(String resourcePath, Resource location)
                                        throws IOException {
                      
                                      Resource requestedResource = location.createRelative(resourcePath);
                                      if (requestedResource.exists() && requestedResource.isReadable()) {
                                        return requestedResource;
                                      }
                      
                                      return new ClassPathResource("/static/index.html");
                      
                                    }
                                  });
                      
                        }
                      
                      }
                      
                      <plugin>
                              <artifactId>maven-clean-plugin</artifactId>
                              <version>${maven-clean-plugin.version}</version>
                              <configuration>
                                <filesets>
                                  <fileset>
                                    <directory>src/main/webapp</directory>
                                    <includes>
                                      <include>*.js</include>
                                      <include>*.txt</include>
                                      <include>*.html</include>
                                      <include>*.css</include>
                                      <include>*.map</include>
                                      <include>*.json</include>
                                      <include>*.ico</include>
                                      <followSymlinks>false</followSymlinks>
                                    </includes>
                                  </fileset>
                                  <fileset>
                                    <directory>src/main/webapp/assets</directory>
                                    <includes>
                                      <include>**</include>
                                      <followSymlinks>false</followSymlinks>
                                    </includes>
                                  </fileset>
                                </filesets>
                              </configuration>
                              <executions>
                                <execution>
                                  <id>auto-clean</id>
                                  <phase>initialize</phase>
                                  <goals>
                                    <goal>clean</goal>
                                  </goals>
                                </execution>
                              </executions>
                            </plugin>
                      
                            <plugin>
                              <artifactId>maven-resources-plugin</artifactId>
                              <executions>
                                <execution>
                                  <id>copy-resources</id>
                                  <phase>process-resources</phase>
                                  <goals>
                                    <goal>copy-resources</goal>
                                  </goals>
                                  <configuration>
                                    <outputDirectory>${project.build.directory}/classes/static</outputDirectory>
                                    <includeEmptyDirs>true</includeEmptyDirs>
                                    <resources>
                                      <resource>
                                        <directory>${basedir}/src/main/${angular.project.name}/dist/${angular.project.name}</directory>
                                        <filtering>true</filtering>
                                      </resource>
                                    </resources>
                                  </configuration>
                                </execution>
                              </executions>
                            </plugin>
                      
                            <plugin>
                              <groupId>com.github.eirslett</groupId>
                              <artifactId>frontend-maven-plugin</artifactId>
                              <version>1.8.0</version>
                              <configuration>
                                <workingDirectory>src/main/${angular.project.name}</workingDirectory>
                              </configuration>
                              <executions>
                                <execution>
                                  <id>install node and npm</id>
                                  <goals>
                                    <goal>install-node-and-npm</goal>
                                  </goals>
                                  <phase>generate-resources</phase>
                                  <configuration>
                                    <nodeVersion>v14.16.1</nodeVersion>
                                  </configuration>
                      
                                </execution>
                                <execution>
                                  <id>npm build angular</id>
                                  <goals>
                                    <goal>npm</goal>
                                  </goals>
                                  <phase>generate-resources</phase>
                                  <configuration>
                                    <arguments>run build:prod</arguments>
                                  </configuration>
                                </execution>
                              </executions>
                            </plugin>
                      
                      @Configuration
                      public class ApplicationWebMvcConfiguration implements WebMvcConfigurer {
                        @Override
                        public void addResourceHandlers(ResourceHandlerRegistry registry) {
                      
                          registry.addResourceHandler("/**")
                                  .addResourceLocations("classpath:/static/")
                                  .resourceChain(true)
                                  .addResolver(new PathResourceResolver() {
                                    @Override
                                    protected Resource getResource(String resourcePath, Resource location)
                                        throws IOException {
                      
                                      Resource requestedResource = location.createRelative(resourcePath);
                                      if (requestedResource.exists() && requestedResource.isReadable()) {
                                        return requestedResource;
                                      }
                      
                                      return new ClassPathResource("/static/index.html");
                      
                                    }
                                  });
                      
                        }
                      
                      }
                      
                      ModelAndView forward() {
                              return new ModelAndView("redirect:/");
                          }
                      

                      Problem trying to display custom error pages with Spring Boot

                      copy iconCopydownload iconDownload
                      <dependency>
                          <groupId>org.springframework.boot</groupId>
                          <artifactId>spring-boot-starter-thymeleaf</artifactId>
                      </dependency>
                      
                      server.error.whitelabel.enabled=false
                      
                       @RequestMapping("/error")
                       public String handleError() {
                          //do something like logging
                          return "error";
                         }
                      }
                      
                       @RequestMapping("/error")
                       public String handleError(HttpServletRequest request) {
                       Object status = 
                       request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
                      
                        if (status != null) {
                          Integer statusCode = Integer.valueOf(status.toString());
                      
                          if(statusCode == HttpStatus.NOT_FOUND.value()) {
                              return "error-404";
                          }
                          else if(statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                              return "error-500";
                          }
                         }
                        return "error";
                      }
                      
                      server.error.whitelabel.enabled=false
                      
                       @RequestMapping("/error")
                       public String handleError() {
                          //do something like logging
                          return "error";
                         }
                      }
                      
                       @RequestMapping("/error")
                       public String handleError(HttpServletRequest request) {
                       Object status = 
                       request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
                      
                        if (status != null) {
                          Integer statusCode = Integer.valueOf(status.toString());
                      
                          if(statusCode == HttpStatus.NOT_FOUND.value()) {
                              return "error-404";
                          }
                          else if(statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                              return "error-500";
                          }
                         }
                        return "error";
                      }
                      
                      server.error.whitelabel.enabled=false
                      
                       @RequestMapping("/error")
                       public String handleError() {
                          //do something like logging
                          return "error";
                         }
                      }
                      
                       @RequestMapping("/error")
                       public String handleError(HttpServletRequest request) {
                       Object status = 
                       request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
                      
                        if (status != null) {
                          Integer statusCode = Integer.valueOf(status.toString());
                      
                          if(statusCode == HttpStatus.NOT_FOUND.value()) {
                              return "error-404";
                          }
                          else if(statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                              return "error-500";
                          }
                         }
                        return "error";
                      }
                      

                      Why mockServer.verify is needed in MockRestServiceServer

                      copy iconCopydownload iconDownload
                      mockServer.expect(requestTo(new URI("https://www.yahoo.com")))
                                      .andExpect(method(HttpMethod.GET)).andRespond(withSuccess());
                              
                      mockServer.expect(requestTo(new URI("https://www.google.com")))
                                      .andExpect(method(HttpMethod.GET)).andRespond(withSuccess());
                              
                              
                      mockServer.expect(requestTo(new URI("https://www.stackoverflow.com")))
                                      .andExpect(method(HttpMethod.GET)).andRespond(withSuccess());
                      
                      restTemplate.getForEntity("https://www.yahoo.com", String.class);
                      restTemplate.getForEntity("https://www.google.com", String.class);
                      

                      How to edit configmap configuration in spring boot kubernetes application during runtime

                      copy iconCopydownload iconDownload
                      kubectl create configmap some-config \
                        --from-file=some-key=some-config.yaml \
                        -n some-namespace \
                        -o yaml \
                        --dry-run | kubectl apply -f - 
                      
                      apiVersion: v1
                      kind: ConfigMap
                      metadata:
                        name: jksconfig
                      data:
                        config.json: |-
                          {{ .Files.Get "config.json" | indent 4 }}
                      
                      #bin/bash
                      kubectl get configmap <configmap-name>  -o yaml > cofig.yaml
                      
                      kubectl create configmap some-config \
                        --from-file=some-key=some-config.yaml \
                        -n some-namespace \
                        -o yaml \
                        --dry-run | kubectl apply -f - 
                      
                      apiVersion: v1
                      kind: ConfigMap
                      metadata:
                        name: jksconfig
                      data:
                        config.json: |-
                          {{ .Files.Get "config.json" | indent 4 }}
                      
                      #bin/bash
                      kubectl get configmap <configmap-name>  -o yaml > cofig.yaml
                      
                      kubectl create configmap some-config \
                        --from-file=some-key=some-config.yaml \
                        -n some-namespace \
                        -o yaml \
                        --dry-run | kubectl apply -f - 
                      
                      apiVersion: v1
                      kind: ConfigMap
                      metadata:
                        name: jksconfig
                      data:
                        config.json: |-
                          {{ .Files.Get "config.json" | indent 4 }}
                      
                      #bin/bash
                      kubectl get configmap <configmap-name>  -o yaml > cofig.yaml
                      
                      apiVersion: v1
                      kind: ConfigMap
                      metadata:
                        name: application-conf
                      data: 
                        {{- if .Values.global.applicationConfiguration }}
                        application.properties: | 
                          {{- .Values.global.applicationConfiguration  | nindent 4 }}
                         {{- end }}
                      

                      Override spring web mvc's default Hibernate Validator

                      copy iconCopydownload iconDownload
                          <bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor">  
                              <property name="validatorFactory" ref="myValidatorFactory"/>  
                          </bean>
                      
                      @Bean
                      public LocalValidatorFactoryBean validator() {
                          LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
                          localValidatorFactoryBean.setMessageInterpolator(new ParameterMessageInterpolator());
                          return localValidatorFactoryBean;
                      }
                      
                      @Bean
                      public MethodValidationPostProcessor methodValidationPostProcessor() {
                          MethodValidationPostProcessor bean = new MethodValidationPostProcessor();
                          bean.setValidator(Validation.byDefaultProvider()
                                  .configure()
                                  // We must use ParameterMessageInterpolator so that we do not need to add a dependency
                                  // on Java Expression Language which is a potential security vulnerability.
                                  // See https://securitylab.github.com/research/bean-validation-RCE/ for more info.
                                  .messageInterpolator(new ParameterMessageInterpolator())
                                  .buildValidatorFactory()
                                  .getValidator());
                          return bean;
                      }
                      
                      @Bean
                      public LocalValidatorFactoryBean validator() {
                          LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
                          localValidatorFactoryBean.setMessageInterpolator(new ParameterMessageInterpolator());
                          return localValidatorFactoryBean;
                      }
                      
                      @Bean
                      public MethodValidationPostProcessor methodValidationPostProcessor() {
                          MethodValidationPostProcessor bean = new MethodValidationPostProcessor();
                          bean.setValidator(Validation.byDefaultProvider()
                                  .configure()
                                  // We must use ParameterMessageInterpolator so that we do not need to add a dependency
                                  // on Java Expression Language which is a potential security vulnerability.
                                  // See https://securitylab.github.com/research/bean-validation-RCE/ for more info.
                                  .messageInterpolator(new ParameterMessageInterpolator())
                                  .buildValidatorFactory()
                                  .getValidator());
                          return bean;
                      }
                      

                      Spring AntPathMatcher with a custom separator behaves strangely

                      copy iconCopydownload iconDownload
                      new AntPathMatcher("\t").match("consentreg", "consentreg");  // true
                      

                      How to initialize Jackson on Spring Boot start to have fast 1st request?

                      copy iconCopydownload iconDownload
                      -verbose:class
                      

                      How to avoid using Kotlin Coroutines' GlobalScope in a Spring WebFlux controller that performs long-running computations

                      copy iconCopydownload iconDownload
                      private val scope = CoroutineScope(Dispatchers.Default)
                      
                      fun route() = coRouter {
                          POST("/big-computation") { request: ServerRequest ->
                              ...
                              scope.launch {
                                  GlobalResultStorage.addResult(runId, longRunningComputation(params))
                              }
                              ...
                          }
                      }
                      

                      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 spring-framework
                      • Use JUnit 5 parallel test execution and still profit from Spring's context caching?
                      • StreamingResponseBody heap usage
                      • Spring Boot 2.6 and Angular in static Resources
                      • EnableLoadTimeWeaving annotation causes application context to fail to load
                      • Problem trying to display custom error pages with Spring Boot
                      • Enabling exception translation for JPA in plain Spring
                      • Why mockServer.verify is needed in MockRestServiceServer
                      • How to edit configmap configuration in spring boot kubernetes application during runtime
                      • Override spring web mvc's default Hibernate Validator
                      • java.net.URI cannot parse domain starting with a number
                      Trending Discussions on spring-framework

                      QUESTION

                      Use JUnit 5 parallel test execution and still profit from Spring's context caching?

                      Asked 2022-Mar-25 at 14:54

                      I am using Spring and JUnit 5.

                      In Spring tests, created contexts are cached so that they don't need to be re-created for each test.

                      However, according to the Spring documentation, this caching does not work when tests are executed in parallel:

                      Test suites and forked processes
                      The Spring TestContext framework stores application contexts in a static cache. This means that the context is literally stored in a static variable. In other words, if tests run in separate processes, the static cache is cleared between each test execution, which effectively disables the caching mechanism.

                      Is there a way, in which one can use JUnit 5's parallel test execution and still profit from Spring's context caching? Is there a parallel execution configuration that still works with Spring's context caching?

                      ANSWER

                      Answered 2022-Mar-25 at 08:15

                      It seems that JUnit 5's parallel test execution works without problems with Spring's test context caching.

                      For parallel test execution, JUnit 5 seems to use a ForkJoinPool under the hood. Multiple threads can access the statically cached Spring test contexts without a problem.

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

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

                      Vulnerabilities

                      No vulnerabilities reported

                      Install spring-framework

                      For access to artifacts or a distribution zip, see the Spring Framework Artifacts wiki page.
                      See the Build from Source Wiki page and the CONTRIBUTING.md file.

                      Support

                      The Spring Framework maintains reference documentation (published and source), Github wiki pages, and an API reference. There are also guides and tutorials across Spring projects.

                      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
                      Explore Kits

                      Save this library and start creating your kit

                      Share this Page

                      share link
                      Consider Popular Model View Controller Libraries
                      Try Top Libraries by spring-projects
                      Compare Model View Controller Libraries with Highest Support
                      Compare Model View Controller Libraries with Highest Quality
                      Compare Model View Controller Libraries with Highest Security
                      Compare Model View Controller Libraries with Permissive License
                      Compare Model View Controller Libraries with Highest Reuse
                      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
                      Explore Kits

                      Save this library and start creating your kit

                      • © 2022 Open Weaver Inc.