SpringFox Issue - spring

I have this issue and I don't know why I checked many times all the files without any answer to fix it hope to find it here and some one faced it before:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-01-10 15:53:21.873 ERROR 35021 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getPatterns()" because "this.condition" is null
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181) ~[spring-context-5.3.14.jar:5.3.14]
at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54) ~[spring-context-5.3.14.jar:5.3.14]
at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356) ~[spring-context-5.3.14.jar:5.3.14]
at java.base/java.lang.Iterable.forEach(Iterable.java:75) ~[na:na]
at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155) ~[spring-context-5.3.14.jar:5.3.14]
at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123) ~[spring-context-5.3.14.jar:5.3.14]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935) ~[spring-context-5.3.14.jar:5.3.14]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586) ~[spring-context-5.3.14.jar:5.3.14]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.2.jar:2.6.2]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730) ~[spring-boot-2.6.2.jar:2.6.2]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412) ~[spring-boot-2.6.2.jar:2.6.2]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) ~[spring-boot-2.6.2.jar:2.6.2]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.2.jar:2.6.2]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1290) ~[spring-boot-2.6.2.jar:2.6.2]
at app.ryadhi.v1.RyadhiApplication.main(RyadhiApplication.java:12) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.6.2.jar:2.6.2]
Caused by: java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getPatterns()" because "this.condition" is null
at springfox.documentation.spring.web.WebMvcPatternsRequestConditionWrapper.getPatterns(WebMvcPatternsRequestConditionWrapper.java:56) ~[springfox-spring-webmvc-3.0.0.jar:3.0.0]
at springfox.documentation.RequestHandler.sortedPaths(RequestHandler.java:113) ~[springfox-core-3.0.0.jar:3.0.0]
at springfox.documentation.spi.service.contexts.Orderings.lambda$byPatternsCondition$3(Orderings.java:89) ~[springfox-spi-3.0.0.jar:3.0.0]
at java.base/java.util.Comparator.lambda$comparing$77a9974f$1(Comparator.java:473) ~[na:na]
at java.base/java.util.TimSort.countRunAndMakeAscending(TimSort.java:355) ~[na:na]
at java.base/java.util.TimSort.sort(TimSort.java:220) ~[na:na]
at java.base/java.util.Arrays.sort(Arrays.java:1307) ~[na:na]
at java.base/java.util.ArrayList.sort(ArrayList.java:1721) ~[na:na]
at java.base/java.util.stream.SortedOps$RefSortingSink.end(SortedOps.java:392) ~[na:na]
at java.base/java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[na:na]
at java.base/java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[na:na]
at java.base/java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[na:na]
at java.base/java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:510) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499) ~[na:na]
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:921) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:682) ~[na:na]
at springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider.requestHandlers(WebMvcRequestHandlerProvider.java:81) ~[springfox-spring-webmvc-3.0.0.jar:3.0.0]
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) ~[na:na]
at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499) ~[na:na]
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:921) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:682) ~[na:na]
at springfox.documentation.spring.web.plugins.AbstractDocumentationPluginsBootstrapper.withDefaults(AbstractDocumentationPluginsBootstrapper.java:107) ~[springfox-spring-web-3.0.0.jar:3.0.0]
at springfox.documentation.spring.web.plugins.AbstractDocumentationPluginsBootstrapper.buildContext(AbstractDocumentationPluginsBootstrapper.java:91) ~[springfox-spring-web-3.0.0.jar:3.0.0]
at springfox.documentation.spring.web.plugins.AbstractDocumentationPluginsBootstrapper.bootstrapDocumentationPlugins(AbstractDocumentationPluginsBootstrapper.java:82) ~[springfox-spring-web-3.0.0.jar:3.0.0]
at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper.start(DocumentationPluginsBootstrapper.java:100) ~[springfox-spring-web-3.0.0.jar:3.0.0]
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:178) ~[spring-context-5.3.14.jar:5.3.14]
... 19 common frames omitted
this is the controller for the file:
package app.ryadhi.v1.API.User;
import app.ryadhi.v1.Domain.File;
import app.ryadhi.v1.Service.FileService;
import app.ryadhi.v1.Utility.Constant.SwaggerConstant;
import app.ryadhi.v1.Utility.Implementations.Service.FileStorageService;
import app.ryadhi.v1.Utility.Payload.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
#RestController
#RequestMapping(path = "/file")
#Api(tags = {SwaggerConstant.API_TAG6})
#CrossOrigin(origins = "*")
public class FileAPI {
private static final Logger logger = LoggerFactory.getLogger(FileAPI.class);
private FileStorageService fileStorageService;
private FileService fileService;
#Autowired
public FileAPI(FileStorageService fileStorageService, FileService fileService) {
this.fileStorageService = fileStorageService;
this.fileService = fileService;
}
#ApiOperation(value = "Uploading File and save it into the database", notes = "saving file into the system", response = File.class)
#ApiResponses({#ApiResponse(responseCode = "200", description = "The file has successfully saved into the system"),
#ApiResponse(responseCode = "500", description = "Successfully saving file"),
#ApiResponse(responseCode = "400", description = "The request is malformed or invalid"),
#ApiResponse(responseCode = "404", description = "The resource URL was not found on the server"),
#ApiResponse(responseCode = "403", description = "You are not authorized. Please authenticate and try again"),
#ApiResponse(responseCode = "401", description = "You don't have permission to this resource")
})
#PostMapping("/upload")
public Response uploadFile(#RequestParam("file") MultipartFile file) {
String fileName = fileStorageService.storeFile(file);
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/downloadFile/")
.path(fileName)
.toUriString();
return new Response(fileName, fileDownloadUri,
file.getContentType(), file.getSize());
}
#ApiOperation(value = "Downloading File from the system", notes = "Downloading file from the system", response = File.class)
#ApiResponses({#ApiResponse(responseCode = "200", description = "The file has successfully saving from the system"),
#ApiResponse(responseCode = "500", description = "Successfully downloading file"),
#ApiResponse(responseCode = "400", description = "The request is malformed or invalid"),
#ApiResponse(responseCode = "404", description = "The resource URL was not found on the server"),
#ApiResponse(responseCode = "403", description = "You are not authorized. Please authenticate and try again"),
#ApiResponse(responseCode = "401", description = "You don't have permission to this resource")
})
#PostMapping("/upload_multi")
public List<Response> uploadMultipleFiles(#RequestParam("files") MultipartFile[] files) {
return Arrays.asList(files)
.stream()
.map(file -> uploadFile(file))
.collect(Collectors.toList());
}
#ApiOperation(value = "Downloading Multiple File from the system", notes = "downloading files from the system", response = File.class)
#ApiResponses({#ApiResponse(responseCode = "200", description = "The files has successfully downloading from the system"),
#ApiResponse(responseCode = "500", description = "Successfully downloading files"),
#ApiResponse(responseCode = "400", description = "The request is malformed or invalid"),
#ApiResponse(responseCode = "404", description = "The resource URL was not found on the server"),
#ApiResponse(responseCode = "403", description = "You are not authorized. Please authenticate and try again"),
#ApiResponse(responseCode = "401", description = "You don't have permission to this resource")
})
#GetMapping("/download/{fileName:.+}")
public ResponseEntity<Resource> downloadFile(#PathVariable String fileName, HttpServletRequest request) {
// Load file as Resource
Resource resource = fileStorageService.loadFileAsResource(fileName);
// Try to determine file's content type
String contentType = null;
try {
contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
} catch (IOException ex) {
logger.info("Could not determine file type.");
}
// Fallback to the default content type if type could not be determined
if (contentType == null) {
contentType = "application/octet-stream";
}
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(contentType))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}
#ApiOperation(value = "Adding files to the user", notes = "Files added to the user", response = File.class)
#ApiResponses({#ApiResponse(responseCode = "200", description = "The files has successfully added to the user"),
#ApiResponse(responseCode = "500", description = "Adding file to the user"),
#ApiResponse(responseCode = "400", description = "The request is malformed or invalid"),
#ApiResponse(responseCode = "404", description = "The resource URL was not found on the server"),
#ApiResponse(responseCode = "403", description = "You are not authorized. Please authenticate and try again"),
#ApiResponse(responseCode = "401", description = "You don't have permission to this resource")
})
#PostMapping("/add_user_file/{id}")
File addFileToUser(#RequestBody File file, #PathVariable Long id) {
return fileService.addFileToUser(file, id);
}
}
this is the swagger configuration:
package app.ryadhi.v1.Utility.Config;
import static app.ryadhi.v1.Utility.Constant.SwaggerConstant.*;
import static java.util.Collections.singletonList;
import static org.springframework.http.HttpHeaders.AUTHORIZATION;
import static springfox.documentation.spi.DocumentationType.SWAGGER_2;
import java.util.Collections;
import java.util.List;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.*;
#Configuration
public class SwaggerConfig {
#Bean
public Docket apiDocket() {
return new Docket(SWAGGER_2).apiInfo(apiInfo())
.forCodeGeneration(true)
.securityContexts(singletonList(securityContext()))
.securitySchemes(singletonList(apiKey()))
.select().apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
.paths(PathSelectors.regex(SECURE_PATH))
.build()
.tags(new Tag(API_TAG, "All APIs relating to Gym Application"));
}
private ApiInfo apiInfo() {
return new ApiInfo(API_TITLE, API_DESCRIPTION, API_VERSION, TERM_OF_SERVICE, contact(),
LICENSE, LICENSE_URL, Collections.emptyList());
}
private Contact contact() {
return new Contact(CONTACT_NAME, CONTACT_URL, CONTACT_EMAIL);
}
private ApiKey apiKey() {
return new ApiKey(SECURITY_REFERENCE, AUTHORIZATION, SecurityScheme.In.HEADER.name());
}
private SecurityContext securityContext() {
return SecurityContext.builder().securityReferences(securityReference()).build();
}
private List<SecurityReference> securityReference() {
AuthorizationScope[] authorizationScope = { new AuthorizationScope(AUTHORIZATION_SCOPE, AUTHORIZATION_DESCRIPTION) };
return singletonList(new SecurityReference(SECURITY_REFERENCE, authorizationScope));
}
#Bean
SecurityConfiguration security() {
return SecurityConfigurationBuilder.builder()
.clientId("test-app-client-id")
.clientSecret("test-app-client-secret")
.realm("test-app-realm")
.appName("test-app")
.scopeSeparator(",")
.additionalQueryStringParams(null)
.useBasicAuthenticationWithAccessCodeGrant(true)
.enableCsrfSupport(false)
.build();
}
#Bean
UiConfiguration uiConfig() {
return UiConfigurationBuilder.builder()
.deepLinking(true)
.displayOperationId(false)
.defaultModelsExpandDepth(1)
.defaultModelRendering(ModelRendering.MODEL)
.displayRequestDuration(true)
.docExpansion(DocExpansion.LIST)
.filter(false)
.maxDisplayedTags(null)
.operationsSorter(OperationsSorter.ALPHA)
.showExtensions(false)
.showCommonExtensions(false)
.tagsSorter(TagsSorter.ALPHA)
.supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS)
.validatorUrl(null)
.build();
}
}
even when I try to re run it never working try to see what's wrong with the main application but there is nothing wrong with it

I found out what is the issue it's about the Springfox dependency all the spring developers facing the same issue after spring 2.6.X
so all of them give the recommendation to migrate to springdoc.
you can find everything here:
https://springdoc.org/#migrating-from-springfox

Spring 2.6.x onwards Sprngfox migrated to SpringDoc. Please use the below dependency with the property. it will enable the swagger.
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.3</version>
</dependency>
//Properties
springdoc.swagger-ui.enabled=true
Reference : https://springdoc.org/#migrating-from-springfox

Related

Spring REST Controller Swagger's default response template error

For JSON requests, the response template on Swagger is showing up properly. However, if I have MultiPartFile as request, the template seems to disappear.
This is the code for controller for MultiPartFile request.
...
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
...
#ApiOperation(value = "Image Update")
#ApiResponses(value = {
#ApiResponse(responseCode = "200", description = "Patch complete",
content = #Content(schema = #Schema(implementation = ProfileDefaultResponseDto.class))),
...
#ApiResponse(responseCode = "500", description = "Server Error")
})
#PatchMapping(value = "/img", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<DefaultResponseDto<Object>> updateImage(HttpServletRequest servletRequest,
#RequestPart(required = false) MultipartFile image) {
...
}
This is what the response template should look like. But it is not showing up like this.

Error while binding parameter from AWS Parameter Store in Spring Boot

Due to some know vulnerabilities, I can't use spring-cloud-starter-aws-parameter-store-config in my org. So I simply tried to extract code from jar and use it in my project. But I'm not able to bind parameter from aws store to spring boot. I'm getting following error-
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'db.username' in value "${db.username}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:178) ~[spring-core-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:124) ~[spring-core-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:236) ~[spring-core-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:210) ~[spring-core-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.lambda$processProperties$0(PropertySourcesPlaceholderConfigurer.java:175) ~[spring-context-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$$Lambda$220/254979217.resolveStringValue(Unknown Source) ~[na:na]
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:908) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1228) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:636) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:116) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:397) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
... 37 common frames omitted
These are the files that I'm using
import com.amazonaws.services.simplesystemsmanagement.AWSSimpleSystemsManagement;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
#Configuration
#EnableConfigurationProperties({AwsParamStoreProperties.class})
#ConditionalOnClass({AWSSimpleSystemsManagement.class, AwsParamStorePropertySourceLocator.class})
#ConditionalOnProperty(
prefix = "aws.paramstore",
name = {"enabled"},
matchIfMissing = true
)
public class AwsParamStoreBootstrapConfiguration {
}
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
#ConfigurationProperties("aws.paramstore")
#Validated
public class AwsParamStoreProperties {
public static final String CONFIG_PREFIX = "aws.paramstore";
#NotNull
#Pattern(
regexp = "(/[a-zA-Z0-9.\\-_]+)*"
)
private String prefix = "/config";
#NotEmpty
private String defaultContext = "application";
#NotNull
#Pattern(
regexp = "[a-zA-Z0-9.\\-_/]+"
)
private String profileSeparator = "_";
private boolean failFast = true;
private String name;
private boolean enabled = true;
public AwsParamStoreProperties() {
}
//Getter and Setters
}
import com.amazonaws.services.simplesystemsmanagement.AWSSimpleSystemsManagement;
import com.amazonaws.services.simplesystemsmanagement.model.GetParametersByPathRequest;
import com.amazonaws.services.simplesystemsmanagement.model.GetParametersByPathResult;
import com.amazonaws.services.simplesystemsmanagement.model.Parameter;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.springframework.core.env.EnumerablePropertySource;
public class AwsParamStorePropertySource extends EnumerablePropertySource<AWSSimpleSystemsManagement> {
private String context;
private Map<String, Object> properties = new LinkedHashMap();
public AwsParamStorePropertySource(String context, AWSSimpleSystemsManagement ssmClient) {
super(context, ssmClient);
this.context = context;
}
public void init() {
GetParametersByPathRequest paramsRequest = (new GetParametersByPathRequest()).withPath(this.context).withRecursive(true).withWithDecryption(true);
this.getParameters(paramsRequest);
}
public String[] getPropertyNames() {
Set<String> strings = this.properties.keySet();
return (String[])strings.toArray(new String[strings.size()]);
}
public Object getProperty(String name) {
return this.properties.get(name);
}
private void getParameters(GetParametersByPathRequest paramsRequest) {
GetParametersByPathResult paramsResult = ((AWSSimpleSystemsManagement)this.source).getParametersByPath(paramsRequest);
Iterator var3 = paramsResult.getParameters().iterator();
while(var3.hasNext()) {
Parameter parameter = (Parameter)var3.next();
String key = parameter.getName().replace(this.context, "").replace('/', '.');
this.properties.put(key, parameter.getValue());
}
if (paramsResult.getNextToken() != null) {
this.getParameters(paramsRequest.withNextToken(paramsResult.getNextToken()));
}
}
}
import com.amazonaws.services.simplesystemsmanagement.AWSSimpleSystemsManagement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.bootstrap.config.PropertySourceLocator;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource;
import org.springframework.util.ReflectionUtils;
public class AwsParamStorePropertySourceLocator implements PropertySourceLocator {
private AWSSimpleSystemsManagement ssmClient;
private AwsParamStoreProperties properties;
private List<String> contexts = new ArrayList();
private Log logger = LogFactory.getLog(this.getClass());
public AwsParamStorePropertySourceLocator(AWSSimpleSystemsManagement ssmClient, AwsParamStoreProperties properties) {
this.ssmClient = ssmClient;
this.properties = properties;
}
public List<String> getContexts() {
return this.contexts;
}
public PropertySource<?> locate(Environment environment) {
if (!(environment instanceof ConfigurableEnvironment)) {
return null;
} else {
ConfigurableEnvironment env = (ConfigurableEnvironment)environment;
String appName = this.properties.getName();
if (appName == null) {
appName = env.getProperty("spring.application.name");
}
List<String> profiles = Arrays.asList(env.getActiveProfiles());
String prefix = this.properties.getPrefix();
String defaultContext = prefix + "/" + this.properties.getDefaultContext();
this.contexts.add(defaultContext + "/");
this.addProfiles(this.contexts, defaultContext, profiles);
String baseContext = prefix + "/" + appName;
this.contexts.add(baseContext + "/");
this.addProfiles(this.contexts, baseContext, profiles);
Collections.reverse(this.contexts);
CompositePropertySource composite = new CompositePropertySource("aws-param-store");
Iterator var9 = this.contexts.iterator();
while(var9.hasNext()) {
String propertySourceContext = (String)var9.next();
try {
composite.addPropertySource(this.create(propertySourceContext));
} catch (Exception var12) {
if (this.properties.isFailFast()) {
this.logger.error("Fail fast is set and there was an error reading configuration from AWS Parameter Store:\n" + var12.getMessage());
ReflectionUtils.rethrowRuntimeException(var12);
} else {
this.logger.warn("Unable to load AWS config from " + propertySourceContext, var12);
}
}
}
return composite;
}
}
private AwsParamStorePropertySource create(String context) {
AwsParamStorePropertySource propertySource = new AwsParamStorePropertySource(context, this.ssmClient);
propertySource.init();
return propertySource;
}
private void addProfiles(List<String> contexts, String baseContext, List<String> profiles) {
Iterator var4 = profiles.iterator();
while(var4.hasNext()) {
String profile = (String)var4.next();
contexts.add(baseContext + this.properties.getProfileSeparator() + profile + "/");
}
}
}
bootstrap.yml
aws:
paramstore:
prefix: /config
name: sample
enabled: true
profileSeparator: _
spring.factories
org.springframework.cloud.bootstrap.BootstrapConfiguration=\com.app.paramstore.AwsParamStoreBootstrapConfiguration

The problems with binding RSocket and gRPC in spring boot

everyone!
I got some idea to use gRPC protobuff code generation implementation as a data layer API to use it instead of POJO in RSocket protocol.
Here is the implementation:
syntax = "proto3";
import "google/protobuf/wrappers.proto";
option java_package = "me.some.protoapi";
option java_multiple_files = true;
message ValidationTaskRequest {
int64 id = 1;
string name = 2;
}
message ValidationTaskResponse {
int64 id = 1;
ValidationStatus status = 2;
ValidationError error = 3;
}
message ValidationError {
string reason = 1;
}
enum ValidationStatus {
PASSED = 0;
DECLINED = 1;
}
RSocket configuration
#Configuration
public class RSocketConfiguration {
#Bean
public RSocket rSocket(#Value("${rsocket.client.port}") int port) {
return RSocketFactory
.connect()
.mimeType(MimeTypeUtils.ALL_VALUE, MimeTypeUtils.ALL_VALUE)
.frameDecoder(PayloadDecoder.ZERO_COPY)
.transport(TcpClientTransport.create(port))
.start()
.retry()
.block();
}
#Bean
public RSocketRequester rSocketRequester(RSocket rSocket, RSocketStrategies rSocketStrategies) {
return RSocketRequester.wrap(
rSocket,
MimeTypeUtils.ALL,
MimeTypeUtils.ALL,
rSocketStrategies
);
}
}
and the service itself
#Service
public class ValidationServiceImpl implements ValidationService {
private final Logger logger = LoggerFactory.getLogger(ValidationServiceImpl.class);
private final TaskService taskService;
private final ReactiveRedisTemplate<String, Task> redis;
private final RSocketRequester rSocketRequester;
private final RedisTopicHelper redisHelper;
#Value("${rsocket.routes.validation}")
private String rSocketValidationRoute;
#Value("${validation.interval}")
private Optional<Integer> validationInterval;
public ValidationServiceImpl(TaskService taskService, ReactiveRedisTemplate<String, Task> redis, RSocketRequester rSocketRequester, RedisTopicHelper redisHelper) {
this.taskService = taskService;
this.redis = redis;
this.rSocketRequester = rSocketRequester;
this.redisHelper = redisHelper;
}
#Override
public void startValidationProcess() {
logger.info("validation listener started");
Flux.interval(Duration.ofMillis(validationInterval.orElse(1000)))
.flatMap(i -> redis.keys(redisHelper.topicAllKeys()))
.flatMap(redis.opsForValue()::get)
.filter(it -> !it.isVerified())
.flatMap(this::requestValidation)
.log()
.metrics()
.subscribe(result -> {
if ( result.getError() != null ) {
logger.error(result.getError().getReason());
} else {
taskService.markTaskAsVerified(result.getId(), result.getStatus());
redis.opsForValue().delete(redisHelper.specifiedTopicWithId(result.getId()));
}
});
}
private Mono<ValidationTaskResponse> requestValidation(Task task) {
return rSocketRequester
.route(rSocketValidationRoute)
.data(
ValidationTaskRequest
.newBuilder()
.setId(task.getId())
.setName(task.getName())
)
.retrieveMono(ValidationTaskResponse.class);
}
}
But, when the spring boot service is starting I caught exception
java.lang.IllegalArgumentException: No decoder for me.some.protoapi.ValidationTaskResponse
at org.springframework.messaging.rsocket.RSocketStrategies.decoder(RSocketStrategies.java:92) ~[spring-messaging-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.messaging.rsocket.DefaultRSocketRequester$DefaultRequestSpec.retrieveMono(DefaultRSocketRequester.java:274) ~[spring-messaging-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.messaging.rsocket.DefaultRSocketRequester$DefaultRequestSpec.retrieveMono(DefaultRSocketRequester.java:258) ~[spring-messaging-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at me.some.test.api.services.validation.ValidationServiceImpl.requestValidation(ValidationServiceImpl.java:73) ~[main/:na]
at reactor.core.publisher.FluxFlatMap$FlatMapMain.onNext(FluxFlatMap.java:378) ~[reactor-core-3.3.2.RELEASE.jar:3.3.2.RELEASE]
at reactor.core.publisher.FluxFilter$FilterSubscriber.onNext(FluxFilter.java:107) ~[reactor-core-3.3.2.RELEASE.jar:3.3.2.RELEASE]
at reactor.core.publisher.FluxFlatMap$FlatMapMain.tryEmit(FluxFlatMap.java:530) ~[reactor-core-3.3.2.RELEASE.jar:3.3.2.RELEASE]
at reactor.core.publisher.FluxFlatMap$FlatMapInner.onNext(FluxFlatMap.java:972) ~[reactor-core-3.3.2.RELEASE.jar:3.3.2.RELEASE]
at reactor.core.publisher.MonoNext$NextSubscriber.onNext(MonoNext.java:76) ~[reactor-core-3.3.2.RELEASE.jar:3.3.2.RELEASE]
at reactor.core.publisher.FluxUsingWhen$UsingWhenSubscriber.onNext(FluxUsingWhen.java:355) ~[reactor-core-3.3.2.RELEASE.jar:3.3.2.RELEASE]
at reactor.core.publisher.FluxMap$MapSubscriber.onNext(FluxMap.java:114) ~[reactor-core-3.3.2.RELEASE.jar:3.3.2.RELEASE]
at reactor.core.publisher.FluxMap$MapSubscriber.onNext(FluxMap.java:114) ~[reactor-core-3.3.2.RELEASE.jar:3.3.2.RELEASE]
at reactor.core.publisher.FluxFilter$FilterSubscriber.onNext(FluxFilter.java:107) ~[reactor-core-3.3.2.RELEASE.jar:3.3.2.RELEASE]
at reactor.core.publisher.MonoNext$NextSubscriber.onNext(MonoNext.java:76) ~[reactor-core-3.3.2.RELEASE.jar:3.3.2.RELEASE]
at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onNext(FluxOnErrorResume.java:73) ~[reactor-core-3.3.2.RELEASE.jar:3.3.2.RELEASE]
at reactor.core.publisher.MonoFlatMapMany$FlatMapManyInner.onNext(MonoFlatMapMany.java:242) ~[reactor-core-3.3.2.RELEASE.jar:3.3.2.RELEASE]
at reactor.core.publisher.FluxConcatMap$ConcatMapImmediate.innerNext(FluxConcatMap.java:274) ~[reactor-core-3.3.2.RELEASE.jar:3.3.2.RELEASE]
at reactor.core.publisher.FluxConcatMap$ConcatMapInner.onNext(FluxConcatMap.java:851) ~[reactor-core-3.3.2.RELEASE.jar:3.3.2.RELEASE]
at reactor.core.publisher.FluxDefaultIfEmpty$DefaultIfEmptySubscriber.onNext(FluxDefaultIfEmpty.java:92) ~[reactor-core-3.3.2.RELEASE.jar:3.3.2.RELEASE]
at reactor.core.publisher.FluxMap$MapSubscriber.onNext(FluxMap.java:114) ~[reactor-core-3.3.2.RELEASE.jar:3.3.2.RELEASE]
at reactor.core.publisher.MonoNext$NextSubscriber.onNext(MonoNext.java:76) ~[reactor-core-3.3.2.RELEASE.jar:3.3.2.RELEASE]
at reactor.core.publisher.MonoNext$NextSubscriber.onNext(MonoNext.java:76) ~[reactor-core-3.3.2.RELEASE.jar:3.3.2.RELEASE]
at io.lettuce.core.RedisPublisher$ImmediateSubscriber.onNext(RedisPublisher.java:888) ~[lettuce-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at io.lettuce.core.RedisPublisher$RedisSubscription.onNext(RedisPublisher.java:281) ~[lettuce-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at io.lettuce.core.RedisPublisher$SubscriptionCommand.complete(RedisPublisher.java:756) ~[lettuce-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at io.lettuce.core.protocol.CommandWrapper.complete(CommandWrapper.java:59) ~[lettuce-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at io.lettuce.core.protocol.CommandHandler.complete(CommandHandler.java:654) ~[lettuce-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at io.lettuce.core.protocol.CommandHandler.decode(CommandHandler.java:614) ~[lettuce-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at io.lettuce.core.protocol.CommandHandler.channelRead(CommandHandler.java:565) ~[lettuce-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:377) ~[netty-transport-4.1.45.Final.jar:4.1.45.Final]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:363) ~[netty-transport-4.1.45.Final.jar:4.1.45.Final]
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:355) ~[netty-transport-4.1.45.Final.jar:4.1.45.Final]
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410) ~[netty-transport-4.1.45.Final.jar:4.1.45.Final]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:377) ~[netty-transport-4.1.45.Final.jar:4.1.45.Final]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:363) ~[netty-transport-4.1.45.Final.jar:4.1.45.Final]
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919) ~[netty-transport-4.1.45.Final.jar:4.1.45.Final]
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:163) ~[netty-transport-4.1.45.Final.jar:4.1.45.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:714) ~[netty-transport-4.1.45.Final.jar:4.1.45.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:650) ~[netty-transport-4.1.45.Final.jar:4.1.45.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:576) ~[netty-transport-4.1.45.Final.jar:4.1.45.Final]
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493) ~[netty-transport-4.1.45.Final.jar:4.1.45.Final]
at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989) ~[netty-common-4.1.45.Final.jar:4.1.45.Final]
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[netty-common-4.1.45.Final.jar:4.1.45.Final]
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[netty-common-4.1.45.Final.jar:4.1.45.Final]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
As you can see, the problem is in decoding proto-models in RSocket transport layer. I know, that gRPC its a binary serializing and it has some magic with binary description below. Has anyone tried to bing this two technologies? Any ideas would be very helpful. Thanks.
I have never faced this problem, but I've configurated my receiver and requester for an JSON payload.
Could you try to set an octet stream mime type for example?
#Bean
RSocket rSocket() {
return RSocketFactory
.connect()
.metadataMimeType("message/x.rsocket.composite-metadata.v0")
.frameDecoder(PayloadDecoder.ZERO_COPY)
.dataMimeType(MimeTypeUtils.APPLICATION_JSON_VALUE)
.transport(TcpClientTransport.create(ztlServerHostname, port))
.start()
.block();
}
#Bean
RSocketRequester rSocketRequester(RSocket rSocket, RSocketStrategies rSocketStrategies) {
return RSocketRequester.wrap(rSocket, MimeTypeUtils.APPLICATION_JSON,
MimeTypeUtils.parseMimeType("message/x.rsocket.composite-metadata.v0"),
rSocketStrategies);
}
The full code is here
May be a ProtobufDecoder() can help you when registered in rsocketStrategies
rsocketRequesterBuilder
.rsocketStrategies(b -> b.decoder(new ProtobufDecoder()))
.connectTcp("localhost",7000)
.block();

Error when running unmodified archetype CXF JAX RS project

I'm trying to run an archetype generated project :
org.apache.cxf.archetype:cxf-jaxrs-service
I used Maven to generate it and tried to run it on tomcat 7.
I posted the code even if its not modified by me (default).
I get the same error with every URL used in the browser.
Am I missing something ?
HelloWorldIT.java
import static org.junit.Assert.assertEquals;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.Response;
import org.apache.cxf.helpers.IOUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.MappingJsonFactory;
import org.junit.BeforeClass;
import org.junit.Test;
public class HelloWorldIT {
private static String endpointUrl;
#BeforeClass
public static void beforeClass() {
endpointUrl = System.getProperty("service.url");
}
#Test
public void testPing() throws Exception {
WebClient client = WebClient.create(endpointUrl + "/hello/echo/SierraTangoNevada");
Response r = client.accept("text/plain").get();
assertEquals(Response.Status.OK.getStatusCode(), r.getStatus());
String value = IOUtils.toString((InputStream)r.getEntity());
assertEquals("SierraTangoNevada", value);
}
#Test
public void testJsonRoundtrip() throws Exception {
List<Object> providers = new ArrayList<Object>();
providers.add(new org.codehaus.jackson.jaxrs.JacksonJsonProvider());
JsonBean inputBean = new JsonBean();
inputBean.setVal1("Maple");
WebClient client = WebClient.create(endpointUrl + "/hello/jsonBean", providers);
Response r = client.accept("application/json")
.type("application/json")
.post(inputBean);
assertEquals(Response.Status.OK.getStatusCode(), r.getStatus());
MappingJsonFactory factory = new MappingJsonFactory();
JsonParser parser = factory.createJsonParser((InputStream)r.getEntity());
JsonBean output = parser.readValueAs(JsonBean.class);
assertEquals("Maple", output.getVal2());
}
}
JsonBean.java
public class JsonBean {
private String val1;
private String val2;
public String getVal1() {
return val1;
}
public void setVal1(String val1) {
this.val1 = val1;
}
public String getVal2() {
return val2;
}
public void setVal2(String val2) {
this.val2 = val2;
}
}
HelloWorld.java
#Path("/hello")
public class HelloWorld {
#GET
#Path("/echo/{input}")
#Produces("text/plain")
public String ping(#PathParam("input") String input) {
return input;
}
#POST
#Produces("application/json")
#Consumes("application/json")
#Path("/jsonBean")
public Response modifyJson(JsonBean input) {
input.setVal2(input.getVal1());
return Response.ok().entity(input).build();
}
}
Error Message :
javax.ws.rs.NotFoundException: HTTP 404 Not Found
at org.apache.cxf.jaxrs.utils.SpecExceptions.toNotFoundException(SpecExceptions.java:89)
at org.apache.cxf.jaxrs.utils.ExceptionUtils.toNotFoundException(ExceptionUtils.java:126)
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.processRequest(JAXRSInInterceptor.java:169)
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.handleMessage(JAXRSInInterceptor.java:77)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:307)
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:251)
at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:223)
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:197)
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:149)
at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:171)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:290)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doGet(AbstractHTTPServlet.java:214)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:265)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
I don't really know anything about the tomcat maven plugin, but going through the configurations in the pom, it appears the port is set to 13000 and the context path to jaxrs-service.
Running mvn tomcat7:run-war from the command line, the following is successful
http://localhost:13000/jaxrs-service/hello/echo/Whatever
I believe the unit test is meant to be ran as an intergration-test goal. You can run
mvn integration-test
and it should start a server and you should see at the end
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
I believe the above solutions starts-up an embedded container, not your actual local instance. If you launch the app from your local instance, then the url should be
http://localhost:8080/<name-of-war>/hello/echo/Whatever

springMVC collections and hibrnate 3.3.2 GA java.lang.Integer cannot be cast to java.lang.Long

Iam getting a bad error on casting.I don't know how to fix it..Please...help me to get out of this.springMVC collections and hibrnate 3.3.2 GA java.lang.Integer cannot be cast to java.lang.Long this exception is not giving any error...still it is not running...........Don't know..........
HTTP Status 500 -
--------------------------------------------------------------------------------
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
root cause
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
com.os.springjpa.controller.BookController.listPaging(BookController.java:103)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
note The full stack trace of the root cause is available in the Apache Tomcat/6.0.20 logs.
--------------------------------------------------------------------------------
Apache Tomcat/6.0.20
## BookController.java ##
package com.os.springjpa.controller;
import javax.validation.Valid;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.os.springjpa.dao.BookDao;
import com.os.springjpa.entity.Book;
import com.os.springjpa.utils.Utils;
/**
* #author kris;
* This class is using Path Variable style as example like Rest
* Style. Path Variable will handling like url string but so simple then
* url string. I'm also still not found how to make url string as simple
* as posible in view layer.
*/
#Controller
#RequestMapping("/book")
public class BookController {
#Autowired
private BookDao bookDao;
private final int PAGE_SIZE = 2;
Logger logger = Logger.getLogger(BookController.class);
#RequestMapping(method = RequestMethod.GET)
public String form(Model model) {
System.out.println(org.hibernate.Version.getVersionString());
model.addAttribute(new Book());
return "book/create";
}
#RequestMapping(method = RequestMethod.POST)
public String create(#Valid Book book, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
logger.info("Error has been detect");
return "book/create";
}
if (bookDao.saveOrUpdate(book)) {
book = bookDao.getByIsbn(book.getIsbn());
return "redirect:/book/" + book.getId();
} else {
return "/exception";
}
}
#RequestMapping(method = RequestMethod.PUT)
public String update(#Valid Book book, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
logger.info("Error has been detect");
return "book/update";
}
if (bookDao.saveOrUpdate(book)) {
return "redirect:/book/" + book.getId();
} else {
return "/exception";
}
}
#RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public String delete(#PathVariable Integer id) {
logger.info("Delete Method Has Call");
Book book = bookDao.getById(id);
if (bookDao.delete(book)) {
return "redirect:/book/list/1";
} else {
return "/exception";
}
}
#RequestMapping(value = "/{id}", method = RequestMethod.GET)
public String detail(#PathVariable Integer id, Model model) {
Book book = bookDao.getById(id);
if (book == null) {
return "/exception";
}
model.addAttribute(book);
return "book/detail";
}
#RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
public String edit(#PathVariable Integer id, Model model) {
Book book = bookDao.getById(id);
if (book == null) {
return "/exception";
}
model.addAttribute(book);
return "book/update";
}
#RequestMapping(value = "/list/{page}", method = RequestMethod.GET)
public String listPaging(#PathVariable Integer page, Model model) {
// Create simple pagination
model.addAttribute("books", bookDao.getAll((page - 1) * PAGE_SIZE, PAGE_SIZE));
model.addAttribute("pageCount", Utils.getPageCount(PAGE_SIZE, (Long)bookDao.countAllBook().get(0)));
return "book/list";
}
}
Utils.java
package com.os.springjpa.utils;
public class Utils {
public static int getPageCount(int pageSize, Long row) {
int result = 0;
if (row % pageSize == 0) {
result = (int) (row / pageSize);
} else {
result = (int) (row / pageSize + 1);
}
return result;
}
}
Please Help me....
Try this,
model.addAttribute("pageCount", Utils.getPageCount(PAGE_SIZE, Long.parseLong(bookDao.countAllBook().get(0).toString())));
In BookController.java line 103
model.addAttribute("pageCount", Utils.getPageCount(PAGE_SIZE,
new Long(bookDao.countAllBook().get(0))));

Resources