UnsupportedSignatureMethodException: HMAC-SHA1 exception in tomcat with jerseyoauth - java

This is my pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mkyong.common</groupId>
<artifactId>RESTfulExample</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>RESTfulExample Maven Webapp</name>
<url>http://maven.apache.org</url>
<repositories>
<repository>
<id>maven2-repository.java.net</id>
<name>Java.net Repository for Maven</name>
<url>http://download.java.net/maven/2/</url>
<layout>default</layout>
</repository>
</repositories>
<properties>
<project.build.java.target>1.6</project.build.java.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.0.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.28</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.5</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>com.sun.jersey.contribs.jersey-oauth</groupId>
<artifactId>oauth-server</artifactId>
<version>1.18</version>
</dependency>
<dependency>
<groupId>com.sun.jersey.contribs.jersey-oauth</groupId>
<artifactId>oauth-signature</artifactId>
<version>1.18</version>
</dependency>
<dependency>
<groupId>com.sun.jersey.contribs.jersey-oauth</groupId>
<artifactId>oauth-client</artifactId>
<version>1.18</version>
</dependency>
</dependencies>
<build>
<finalName>RESTfulExample</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.3.1</version>
<configuration>
<complianceLevel>1.6</complianceLevel>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<!--<goal>test-compile</goal> -->
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
This is my oath filter class
public class OAuthAuthenticationFilter1 implements ContainerRequestFilter {
public ContainerRequest filter(ContainerRequest containerRequest) {
OAuthServerRequest request = new OAuthServerRequest(containerRequest);
OAuthParameters params = new OAuthParameters();
params.readRequest(request);
OAuthSecrets secrets = new OAuthSecrets();
OAuthParameters param=new OAuthParameters();
secrets.consumerSecret("OwnAccount");
param.consumerKey("OwnAccount");
try {
if(!OAuthSignature.verify(request, params, secrets)) {
throw new WebApplicationException(401);
}
} catch (OAuthSignatureException e) {
throw new WebApplicationException(e, 401);
}
return containerRequest;
}
}
This is my client
public class Sample1 {
public static final String HOSTNAME = "http://localhost:8080/RESTfulExample/rest/hello/planetext";
public static final String CONSUMER_KEY = "OwnAccount";
public static final String CONSUMER_SECRET = "OwnAccount";
/**
* #param args
*/
public static void main(String[] args) {
Client client = Client.create();
OAuthParameters params = new OAuthParameters().signatureMethod("HMAC-SHA1").consumerKey(CONSUMER_KEY);
OAuthSecrets secrets = new OAuthSecrets().consumerSecret(CONSUMER_SECRET);
OAuthClientFilter filter = new OAuthClientFilter(client.getProviders(), params, secrets);
WebResource res = client.resource(HOSTNAME );
res.addFilter(filter);
String responseString = res.get(String.class);
System.out.println(responseString);
}
}
I am using following oath and jersey pom referring the site
http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.sun.jersey.contribs.jersey-oauth%22
<dependency>
<groupId>com.sun.jersey.contribs.jersey-oauth</groupId>
<artifactId>oauth-server</artifactId>
<version>1.18</version>
</dependency>
<dependency>
<groupId>com.sun.jersey.contribs.jersey-oauth</groupId>
<artifactId>oauth-signature</artifactId>
<version>1.18</version>
</dependency>
<dependency>
<groupId>com.sun.jersey.contribs.jersey-oauth</groupId>
<artifactId>oauth-client</artifactId>
<version>1.18</version>
</dependency>
When following code on filter class is called
try {
// exception is thrown from here
if(!OAuthSignature.verify(request, params, secrets)) {
throw new WebApplicationException(401);
}
} catch (OAuthSignatureException e) {
throw new WebApplicationException(e, 401);
}
I am getting this exception
com.sun.jersey.oauth.signature.UnsupportedSignatureMethodException: HMAC-SHA1
at com.sun.jersey.oauth.signature.OAuthSignature.getSignatureMethod(OAuthSignature.java:257)
I am using tomcat 7.
I searched on the net but could not find the cause for tomcat .What i am missing ?Do any one has faced it for tomcat ?

I solved this problem when i updated jersey-server jar to 1.18.I was using jersey-server 1.8 jar before.

Related

Java Lambda for spring-cloud version to 3.2.3/3.1.7 org/springframework/boot/ApplicationContextFactory: java.lang.NoClassDefFoundError

I'm trying change version for spring-cloud-function-adapter-aws from 3.0.7.RELEASE to either 3.1.7 or 3.2.3 (as Spring Cloud Function Vulnerability CVE-2022-22963) but getting error as it is not able to find the class
java.lang.NoClassDefFoundError: org/spring framework/boot/ApplicationContextFactory
at org.springframework.cloud.function.context.FunctionalSpringApplication.(FunctionalSpringApplication.java:67)
at org.springframework.cloud.function.context.AbstractSpringFunctionAdapterInitializer.springApplication(AbstractSpringFunctionAdapterInitializer.java:378)
at org.springframework.cloud.function.context.AbstractSpringFunctionAdapterInitializer.initialize(AbstractSpringFunctionAdapterInitializer.java:121)
at org.springframework.cloud.function.adapter.aws.SpringBootStreamHandler.initialize(SpringBootStreamHandler.java:61)
at org.springframework.cloud.function.adapter.aws.SpringBootStreamHandler.handleRequest(SpringBootStreamHandler.java:53)
Caused by: java.lang.ClassNotFoundException:
My Application.java
#ComponentScan
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
FunctionConfiguration.java
#Configuration
public class FunctionConfiguration {
private static Logger logger = LoggerFactory.getLogger(FunctionConfiguration.class);
#Autowired
ActionService service;
#Bean
public Function<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> containerService() {
return value -> {
try {
APIGatewayProxyResponseEvent responseEvent = checkHttpMethod(value);
if (responseEvent != null) {
responseEvent.setBody("Option Method");
return responseEvent;
} else {
return createResponseEvent(value);
}
} catch (Exception e) {
return new APIGatewayProxyResponseEvent().withBody(e.getMessage()).withStatusCode(500)
.withHeaders(createResultHeader(value));
}
};
}
private APIGatewayProxyResponseEvent checkHttpMethod(APIGatewayProxyRequestEvent event) {
APIGatewayProxyResponseEvent responseEvent = new APIGatewayProxyResponseEvent();
if (event.getHttpMethod() != null && event.getHttpMethod().equalsIgnoreCase("options")) {
responseEvent.setHeaders(createResultHeader(event));
responseEvent.setStatusCode(200);
return responseEvent;
} else
return null;
}
private APIGatewayProxyResponseEvent createResponseEvent(APIGatewayProxyRequestEvent event) {
APIGatewayProxyResponseEvent responseEvent = new APIGatewayProxyResponseEvent();
try {
responseEvent = service.actionMethod(event);
responseEvent.setHeaders(createResultHeader(event));
return responseEvent;
} catch (Exception e) {
logger.error("Error executing method", e);
responseEvent.setHeaders(createResultHeader(event));
responseEvent.setBody(e.getMessage());
responseEvent.setStatusCode(500);
return responseEvent;
}
}
private Map<String, String> createResultHeader(APIGatewayProxyRequestEvent event) {
Map<String, String> resultHeader = new HashMap<>();
resultHeader.put("Content-Type", "application/json");
resultHeader.put("Access-Control-Allow-Headers", "Content-Type");
resultHeader.put("Vary", "Origin");
try {
String origin = event.getHeaders().get("origin");
resultHeader.put("Access-Control-Allow-Origin", origin);
} catch (Exception e) {
logger.error("origin not exist to add");
}
resultHeader.put("Access-Control-Allow-Credentials", "true");
logger.info(" Headers added ");
return resultHeader;
}
}
pom.xml
4.0.0
com.app.lambda
springBootLambda
1.0.3
springBootLambda
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.0.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<aws-lambda-java-core.version>1.2.1</aws-lambda-java-core.version>
<spring-cloud-function.version>3.0.7.RELEASE
</spring-cloud-function.version>
<wrapper.version>1.0.17.RELEASE</wrapper.version>
<aws-lambda-java-events.version>2.2.7</aws-lambda-java-events.version>
<aws-java-sdk-s3.version>1.11.792</aws-java-sdk-s3.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-indexer</artifactId>
<scope>optional</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-function-adapter-aws</artifactId>
<version>${spring-cloud-function.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>${aws-lambda-java-core.version}</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.11.672</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-core</artifactId>
<version>1.11.672</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-events</artifactId>
<version>${aws-lambda-java-events.version}</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot.experimental</groupId>
<artifactId>spring-boot-thin-layout</artifactId>
<version>${wrapper.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<configuration>
<finalName>${project.artifactId}-${project.version}</finalName>
<createDependencyReducedPom>false</createDependencyReducedPom>
<shadedArtifactAttached>true</shadedArtifactAttached>
<shadedClassifierName>shaded</shadedClassifierName>
</configuration>
</plugin>
</plugins>
</build>
serverless.yml
service: SpringBoot-Lambda
provider:
name: aws
runtime: java8
region: us-east-1
memory: 2048
timeout: 40
spring:
jpa:
hibernate.ddl-auto: update
generate-ddl: true
show-sql: true
jar file that will be uploaded and executed on AWS
package:
artifact: target/{project.artifactId}-${project.version}.jar
#define Lambda function
functions:
createMethod:
handler: org.springframework.cloud.function.adapter.aws.SpringBootStreamHandler
events: # api gateway
- http:
path: pass
method: post
cors: true
environment: # environment variables
FUNCTION_NAME: SpringBoot-Lambda
You need to upgrade Spring Boot as well. You are using 2.3.0 and ApplicationContextFactory was added in 2.4, but 2.4.x is no longer supported.
You should upgrade to Spring Boot 2.5.12 or 2.6.6.

Jersey Rest Web Service with POJO Mapping remove fields with null values from JSON String [SOLVED]

I have a Jersey Rest Web Service and I would like to send json response removing all fields with null values from json response.
I'm using
#JsonInclude(JsonInclude.Include.NON_NULL)
but it doesn't work at both class and attribute level.
My resource class contain this function:
#RolesAllowed("ADMIN")
#Path("/test")
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
#ApiOperation(value = "test Create", response = TestResponse.class)
public Response Create(TestRequest request, #Context ContainerRequestContext context) {
TestResponse resp = new TestResponse();
resp.setValueA("Value A");
return Response.ok().entity(resp).build();
}
TestResponse class contain:
#ApiModel("TestResponse")
#JsonInclude(JsonInclude.Include.NON_NULL)
public class TestResponse{
#JsonProperty
private String valueA;
#JsonProperty
private String valueB;
#ApiModelProperty(value = "Value A", example = "value A")
public String getValueA(){
return valueA;
}
public SetValueA(String valueA){
this.valueA = valueA;
}
#ApiModelProperty(value = "Value B", example = "value B")
public String getValueB(){
return valueB;
}
public SetValueB(String valueB){
this.valueB = valueB;
}
}
my JSON response contain:
{"valueA":"ValueA","valueB":null}
but I would like to send back this JSON:
{"valueA":"ValueA"}
this is my application class:
#ApplicationPath("/rest")
public class App extends ResourceConfig {
public App() {
packages("it.ivan");
// Register Auth Filter here
register(AuthenticationFilter.class);
register(StartupHandler.class);
register(MultiPartFeature.class);
register(new LoggingFeature(Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME),
Level.INFO, LoggingFeature.Verbosity.PAYLOAD_ANY, 10000));
BeanConfig beanConfig = new BeanConfig();
beanConfig.setTitle("Ivan Rest Application");
beanConfig.setVersion("1.0.0");
beanConfig.setBasePath("/rest/");
beanConfig.setResourcePackage("it.ivan");
beanConfig.setScan(true);
register(beanConfig);
register(io.swagger.jaxrs.listing.ApiListingResource.class);
register(io.swagger.jaxrs.listing.SwaggerSerializers.class);
register(io.swagger.jaxrs.config.DefaultJaxrsConfig.class);
Swagger swagger = new Swagger();
swagger.securityDefinition("basicAuth", new BasicAuthDefinition());
new SwaggerContextService().updateSwagger(swagger);
}
}
this is my pom.xml file:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>it.ivan</groupId>
<artifactId>TestRest</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>TestRest</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jersey.version>2.33</jersey.version>
<slf4j.version>1.7.29</slf4j.version>
</properties>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.1</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>com.owlike</groupId>
<artifactId>genson</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20201115</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.4.0-b180830.0359</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-jersey2-jaxrs</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
</dependencies>
UPDATE... ISSUE SOLVED...
I removed this dependecy:
<dependency>
<groupId>com.owlike</groupId>
<artifactId>genson</artifactId>
<version>1.6</version>
</dependency>
and I added this one:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
</dependency>

quarkus runtimeException "Bad type on operand stack"

I have an error when creating a jwt token encoded in base 64.
The error that is returned is this one:
Caused by:**
java.lang.ExceptionInInitializerError
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at java.lang.Class.newInstance(Class.java:442)
at io.quarkus.runner.RuntimeRunner.run(RuntimeRunner.java:142)
at io.quarkus.test.junit.QuarkusTestExtension.doJavaStart(QuarkusTestExtension.java:248)
at io.quarkus.test.junit.QuarkusTestExtension.createTestInstance(QuarkusTestExtension.java:390)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstanceFactory(ClassBasedTestDescriptor.java:285)
... 49 more
Caused by: java.lang.RuntimeException: Failed to start quarkus
at io.quarkus.runner.ApplicationImpl1.<clinit>(ApplicationImpl1.zig:413)
... 58 more
Caused by: java.lang.VerifyError: Bad type on operand stack
Exception Details:
Location:
com/ciwara/kalanSowApp/security/TokenProvider.validateToken(Ljava/lang/String;)Z #42: invokeinterface
Reason:
Type 'java/lang/Object' (current frame, stack[2]) is not assignable to 'java/lang/Throwable'
#ApplicationScoped
public class TokenProvider {
private final Logger log = LoggerFactory.getLogger(TokenProvider.class);
#Inject
private KalanSowAppConfiguration applicationConfiguration;
private static final String AUTHORITIES_KEY = "auth";
private Key key;
private long tokenValidityInMilliseconds;
private long tokenValidityInMillisecondsForRememberMe;
#PostConstruct
public void init() {
byte[] keyBytes;
String secret = applicationConfiguration.jwtConfiguration.base64Secret;
if (secret == null || secret.trim().equals("")) {
keyBytes = "".getBytes(StandardCharsets.UTF_8);
log.info("Using secret key", keyBytes);
} else {
log.info("Using a Base64-encoded JWT secret key");
keyBytes = Decoders.BASE64.decode(secret);
log.info("Using a Base64-encoded JWT secret key", keyBytes);
}
this.key = Keys.hmacShaKeyFor(keyBytes);
this.tokenValidityInMilliseconds = 1000 * applicationConfiguration.jwtConfiguration.tokenValidityInSeconds;
this.tokenValidityInMillisecondsForRememberMe = 1000
* applicationConfiguration.jwtConfiguration.tokenValidityInSecondsForRememberMe;
}
public String createToken(JwtPrincipal principal, boolean rememberMe) {
long now = (new Date()).getTime();
Date validity;
if (rememberMe) {
validity = new Date(now + this.tokenValidityInMillisecondsForRememberMe);
} else {
validity = new Date(now + this.tokenValidityInMilliseconds);
}
return Jwts.builder().setSubject(principal.getName()).claim(AUTHORITIES_KEY, principal.getAuthorities())
.signWith(this.key, SignatureAlgorithm.HS512).setExpiration(validity).compact();
}
public Principal getPrincipal(String token) {
Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
String[] roles = null;
if (claims.get(AUTHORITIES_KEY) != null) {
Collection<String> authorities = Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(","))
.collect(Collectors.toList());
roles = (String[]) authorities.toArray();
}
return new JwtPrincipal(claims.getSubject(), roles);
}
public boolean validateToken(String authToken) throws ExceptionInInitializerError {
try {
// OK, we can trust this JWT
Jwts.parser().setSigningKey(key).parseClaimsJws(authToken);
return true;
} catch (io.jsonwebtoken.security.SecurityException | MalformedJwtException e) {
// don't trust the JWT!
log.info("Invalid JWT signature.");
log.trace("Invalid JWT signature trace: {}", e);
} catch (ExpiredJwtException e) {
log.info("Expired JWT token.");
log.trace("Expired JWT token trace: {}", e);
} catch (UnsupportedJwtException e) {
log.info("Unsupported JWT token.");
log.trace("Unsupported JWT token trace: {}", e);
} catch (IllegalArgumentException e) {
log.info("JWT token compact of handler are invalid.");
log.trace("JWT token compact of handler are invalid trace: {}", e);
}
// don't trust the JWT!
return false;
}
}
I don't understang where is a problem of bad type on operand stack issue.
Config class is
#ConfigProperties(prefix = "application")
public class KalanSowAppConfiguration {
public JwtConfiguration jwtConfiguration = new JwtConfiguration();
#ConfigProperties(prefix = "application.jwtConfiguration")
public static class JwtConfiguration {
#ConfigProperty(name = "base64-secret")
public String base64Secret;
#ConfigProperty(name = "tokenValidityInSeconds", defaultValue = "300")
public long tokenValidityInSeconds;
#ConfigProperty(name = "tokenValidityInSecondsForRememberMe", defaultValue = "7200")
public long tokenValidityInSecondsForRememberMe;
}
public JwtConfiguration getJwtConfiguration() {
return jwtConfiguration;
}
public void setJwtConfiguration(JwtConfiguration jwtConfiguration) {
this.jwtConfiguration = jwtConfiguration;
}
}
Configuration class read application.properties file. properties file contain the secret key and base64Secret to generate token.
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ciwara.kalanSowApp</groupId>
<artifactId>kalanSow-Backend</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<surefire-plugin.version>2.22.0</surefire-plugin.version>
<maven.compiler.parameters>true</maven.compiler.parameters>
<quarkus.version>0.26.1</quarkus.version>
<compiler-plugin.version>3.8.1</compiler-plugin.version>
<maven.compiler.source>1.8</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.target>1.8</maven.compiler.target>
<jboss-logging.version>3.3.2.Final</jboss-logging.version>
<nimbus-jose.version>8.4</nimbus-jose.version>
<mockito.version>3.2.4</mockito.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-bom</artifactId>
<version>${quarkus.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- <dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-arc</artifactId>
<scope>provided</scope>
</dependency> -->
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy-jsonb</artifactId>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-rest-client</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.10.7</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.10.7</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.10.7</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<version>${nimbus-jose.version}</version>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
</dependency>
<!-- <dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
</dependency> -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-jdbc-postgresql</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/io.quarkus/quarkus-jdbc-h2 -->
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-jdbc-h2</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/io.quarkus/quarkus-jdbc-h2 -->
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-test-h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-orm-panache</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-orm</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-security</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-smallrye-openapi</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-smallrye-metrics</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-smallrye-health</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-spring-web</artifactId>
</dependency>
<!-- <dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-undertow</artifactId>
</dependency> -->
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-spring-di</artifactId>
</dependency>
<!-- <dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web-client</artifactId>
</dependency> -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-maven-plugin</artifactId>
<version>${quarkus.version}</version>
<executions>
<execution>
<goals>
<goal>build</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>${compiler-plugin.version}</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire-plugin.version}</version>
<configuration>
<systemProperties>
<java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
</systemProperties>
</configuration>
</plugin>
<!-- <plugin>
<groupId>org.jboss.jandex</groupId>
<artifactId>jandex-maven-plugin</artifactId>
<version>1.0.7</version>
</plugin> -->
</plugins>
</build>
<profiles>
<profile>
<id>native</id>
<activation>
<property>
<name>native</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-maven-plugin</artifactId>
<version>${quarkus.version}</version>
<executions>
<execution>
<goals>
<goal>native-image</goal>
</goals>
<configuration>
<enableHttpUrlHandler>true</enableHttpUrlHandler>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${surefire-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
<configuration>
<systemProperties>
<native.image.path>${project.build.directory}/${project.build.finalName}-runner</native.image.path>
</systemProperties>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>default</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<junit.includes>**/*Test.java</junit.includes>
<junit.excludes>**/*Test.java</junit.excludes>
</properties>
</profile>
</profiles>
</project>

AWS lambda + spring boot = not wiring component

I´m trying to use spring-boot inside my AWS lambda application to make calls to a SOAP web-service. But looks like it isn´t autowiring my SOAP component.
Here´s my code:
#SpringBootApplication(scanBasePackages={"com.fenix"})
#EnableAutoConfiguration
#ComponentScan
public class Aplicacao extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Aplicacao.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder springApplicationBuilder) {
return springApplicationBuilder.sources(Aplicacao.class);
}
}
#Configuration
public class Beans {
#Bean
public Jaxb2Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setPackagesToScan("com.tranzaxis.schemas", "org.radixware.schemas", "org.xmlsoap.schemas", "com.compassplus.schemas");
return marshaller;
}
#Bean
public TranClient tranClient(Jaxb2Marshaller marshaller) {
TranClient client = new TranClient();
client.setDefaultUri("http://rhel72.tx:12301?wsdl");
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
return client;
}
#Bean(name = "Tran")
public TranClient getTranClient() {
return tranClient(marshaller());
}
}
public class PostMovimentacao extends Handler implements Service {
#Autowired
#Qualifier("Tran")
private TranClient tranClient;
#Inject
private PessoaCompassBO pessoaCompassBO;
private CompassConfig compassConfig;
private static final Logger LOGGER = Logger.getLogger(PostMovimentacao.class);
#Override
protected ResponseEntity execute(ApiRequest request, Context context) throws HttpException {
MovimentacaoRequest movimentacaoRequest = new MovimentacaoRequest();
movimentacaoRequest.setOrigem(669L);
movimentacaoRequest.setDestino(657L);
movimentacaoRequest.setValor(BigDecimal.valueOf(1L));
TranInvoke invoke = tranClient.movimentacaoFinanceira(movimentacaoRequest, compassConfig); -->NullPointer here
return ResponseEntity.of(Optional.of(invoke), Optional.empty(), HttpStatus.SC_OK);
}
#Override
public void setup() {
try {
compassConfig = CompassConfig.build();
} catch (InvalidConfigException e) {
LOGGER.error("Compass config error", e);
}
}
}
Here´s my pom.xml:
<build>
<finalName>integrador-compass</finalName>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.5.6.RELEASE</version>
<configuration>
<layout>MODULE</layout>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.pitest</groupId>
<artifactId>pitest-maven</artifactId>
<version>1.1.11</version>
<configuration>
<targetClasses>
<param>com.fenix.*</param>
</targetClasses>
<excludedClasses>
<excludedClasse>com.fenix.handler.request*</excludedClasse>
<excludedClasse>com.fenix.handler.response*</excludedClasse>
<excludedClasse>com.fenix.model*</excludedClasse>
</excludedClasses>
<avoidCallsTo>
<avoidCallsTo>java.util.logging</avoidCallsTo>
<avoidCallsTo>org.apache.log4j</avoidCallsTo>
<avoidCallsTo>org.slf4j</avoidCallsTo>
<avoidCallsTo>org.apache.commons.logging</avoidCallsTo>
</avoidCallsTo>
<timestampedReports>false</timestampedReports>
<outputFormats>
<outputFormat>XML</outputFormat>
<outputFormat>HTML</outputFormat>
</outputFormats>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<configuration>
<includes>
<include>**/*Tests.java</include>
<include>**/*Test.java</include>
</includes>
</configuration>
</plugin>
</plugins>
<extensions>
<extension>
<groupId>org.springframework.build</groupId>
<artifactId>aws-maven</artifactId>
<version>5.0.0.RELEASE</version>
</extension>
</extensions>
</build>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
</dependency>
<dependency>
<groupId>com.fenix</groupId>
<artifactId>compass-api</artifactId>
<version>0.0.15</version>
</dependency>
<dependency>
<groupId>com.fenix</groupId>
<artifactId>lambda-commons</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.5.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.mashape.unirest</groupId>
<artifactId>unirest-java</artifactId>
<version>1.4.9</version>
</dependency>
</dependencies>
Has anyone already used this configuration? I added spring-boot cause it was the only way to make my SOAP calls. If I try to make call just using code from WSDL, when it tries to connect to server, I got an error saying that request was empty. With spring-boot it doesn´t need to connect first, it just sends the request and it works fine.
Any help is welcome.
Thanks a lot.
Apparently, the Spring Boot application context is not being initialized in your code...If you really want to use Spring Boot in your Lambda Function you could try something like:
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-core</artifactId>
<version>1.11.181</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-lambda</artifactId>
<version>1.11.181</version>
</dependency>
</dependencies>
Service Example:
#Component
public class MyService {
public void doSomething() {
System.out.println("Service is doing something");
}
}
Some Bean Example:
#Component
public class MyBean {
#Autowired
private MyService service;
public void executeService() {
service.doSomething();
}
}
A Lambda Handler Example:
#SpringBootApplication
public class LambdaHandler implements RequestHandler<Request, Response> {
private ApplicationContext getApplicationContext(String [] args) {
return new SpringApplicationBuilder(LambdaHandler.class)
.web(false)
.run(args);
}
public Response handleRequest(Request input, Context context) {
ApplicationContext ctx = getApplicationContext(new String[]{});
MyBean bean = ctx.getBean(MyBean.class);
bean.executeService();
return new Response();
}
}

Spring Executable jar not saving in DB, It works with Eclipse

I have a SpringBoot App, that works as expected when I run it with Eclipse. I create a runnable jar and test it. Everything works expect one thing: it does not save anything on the DB, there is no log or exception to check. I assume there has to be something with the export, because it does not store anything,
not even running it locally.
I have two projects, one depending from the other.
The project POM.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>BatchCare</groupId>
<artifactId>BatchCare</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
</parent>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.4.2.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.simpleframework</groupId>
<artifactId>simple-xml</artifactId>
<version>2.6.9</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.1.0.7.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
<!-- <version>1.3.2</version> -->
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>CareLibrary</groupId>
<artifactId>CareLibrary</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.156</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
<repository>
<id>local-repo</id>
<name>Local Project Repo</name>
<url>file://${basedir}/lib/</url>
<layout>default</layout>
</repository>
</repositories>
Classes:
#ComponentScan({"ar.com.tr.latam.care.utils", "ar.com.tr.latam.care.unification.process", "ar.com.tr.latam.care.repository"})
#EnableJpaRepositories
//#Component
#Repository
public class RequestLoggerImpl implements RequestLogger {
/**
* Log.
*/
private static final Logger LOG = LoggerFactory.getLogger(RequestLoggerImpl.class);
#Autowired
private RequestLogDao requestLogDao;
#Override
public void log() {
RequestLog requestLog = new RequestLog();
requestLog.setDate(new Date());
requestLog.setSource("jar");
try {
requestLogDao.save(requestLog);
} catch (Exception ex) {
System.out.println("-------------ERROR-------------------");
ex.printStackTrace();
}
}
}
RequestLogDAO
public interface RequestLogDao extends CrudRepository<RequestLog, Integer> {
}
RquestLog
#Entity
#Table(name = "REQUEST_LOG")
public class RequestLog {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "RequestLogSeq")
#SequenceGenerator(name = "RequestLogSeq", sequenceName = "REQUEST_LOG_SEQ")
private Integer id;
#Column
#NotNull
private Date date;
#NotNull
private String source;
public void setDate(Date date) {
this.date = date;
}
public void setSource(String source) {
this.source = source;
}
}
}
My main Class:
#ComponentScan({"ar.com.tr.latam.care", "ar.com.tr.latam.care.repository", "ar.com.tr.latam.care.filtro"})
#EnableJpaRepositories
#SpringBootApplication
public class InitBatch implements CommandLineRunner {
#Autowired
private Batch batch;
#Override
public void run(String... args) throws Exception {
batch.processFiles();
}
public static void main(String[] args) throws Exception {
long startTime = System.nanoTime();
SpringApplication.run(InitBatch.class, args).close();
System.out.println(String.format("Total process time (%s) seconds",(System.nanoTime() - startTime) / 1000000000));
}
}
How do I export the project? First, I do a mvn clean install for the Library project . After this I go to my Project and do mvn clean package.
This creates a Runnable jar that works, expect for this problem that can't save anyhing on the DB.
Also, the RequestLogDao is made with JPA.
Any help? Thanks in advance!

Categories