In my local machine my rest API run perfectly. But i hosted in the server. Then when i call a post method it return error. But GET method working perfectly. Both methods working in my local computer. This is my error
Following is my 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>com.Mobios</groupId>
<artifactId>DigitalWallet</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.0.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.6.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.12.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.thetransactioncompany/cors-filter -->
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>cors-filter</artifactId>
<version>2.6</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
And this is my method
#RequestMapping(value = "/origin/sendcredit/", method = RequestMethod.POST)
// #Transactional(rollbackFor = DWException.class)
public String addSubCredit(
#RequestBody AddMoneyToOriginVM sendCreditToOriginVM/* ,#RequestParam("hashedValue") String hashedValue */,
HttpServletResponse response) throws Exception {
// checkPlainAndHashed.check("ascc","cdscwc");
// Log4JUtil.logger.info("SendCredit|Start|Transaction=" + sendCreditToOriginVM.toString() + "|"
// + sendCreditToOriginVM.getSender_mobile_number() + " to "
// + sendCreditToOriginVM.getReceiver_mobile_number() + " amount " + sendCreditToOriginVM.getAmount() + "|"
// + sendCreditToOriginVM.getTransaction_Type_id());
String Text = "";
try {
String receiver = sendCreditToOriginVM.getReceiver_mobile_number();
String sender = sendCreditToOriginVM.getSender_mobile_number();
int pin = sendCreditToOriginVM.getSender_pin();
double amount = sendCreditToOriginVM.getAmount();
try {
Origin dbReceiver = originService.findByNumber(receiver);
Origin dbSender = originService.findByNumber(sender);
if (originService.findByNumberAndPin(sender, pin) != null) {
double a = Double.parseDouble(encodeDecode.Decode(dbSender.getWallet().getAmount()));
if (a < amount) {
throw new InsufficientBalanceException();
} else {
if (dbReceiver == null) {
OriginVM newOrigin = new OriginVM();
newOrigin.setMobile_number(receiver);
newOrigin.setOrigin_types_id(3);
newOrigin.setSuper_mobile_number(sender);
newOrigin.setStatus_id(1);
newOrigin.setSuper_pin(pin);
newOrigin.setWallet_amount(amount);
newOrigin.setMembership_types_id(5);
newOrigin.setTransaction_Type_id(1);
addOrigin(newOrigin, response);
} else {
SaveTransaction(dbSender, dbReceiver, amount, 2, "Debit", "Credit");
}
dbReceiver = originService.findByNumber(receiver);
dbSender = originService.findByNumber(sender);
try {
Text = "0|Transaction Successfull"
+ encodeDecode.Decode(String.valueOf(dbReceiver.getWallet().getAmount())) + "|"
+ encodeDecode.Decode(String.valueOf(dbSender.getWallet().getAmount()));
} catch (Exception e) {
throw new RuntimeException("Roll Me Back");
}
Log4JUtil.logger.info("SendCredit|End|Transaction=" + sendCreditToOriginVM.toString() + "|"
+ sendCreditToOriginVM.getSender_mobile_number() + " to "
+ sendCreditToOriginVM.getReceiver_mobile_number() + " amount "
+ sendCreditToOriginVM.getAmount() + "|"
+ sendCreditToOriginVM.getTransaction_Type_id());
}
} else {
throw new AgentValidationFailedException();
}
} catch (DWException exp) {
throw exp;
}
} catch (DWException ex) {
// Log4JUtil.logger.info("Origine|Exception|Transaction=" + sendCreditToOriginVM.toString() + "|"
// + sendCreditToOriginVM.getSender_mobile_number() + " to "
// + sendCreditToOriginVM.getReceiver_mobile_number() + " amount " + sendCreditToOriginVM.getAmount()
// + "|" + ex.toString());
response.sendError(ex.getErrorCode(), ex.getErrorMessage());
}
return Text;
}
This is Server Java version
openjdk version "1.8.0_191"
OpenJDK Runtime Environment (build 1.8.0_191-b12)
OpenJDK 64-Bit Server VM (build 25.191-b12, mixed mode)
Related
I am trying to use the alpha vantage scraper api from https://github.com/mainstringargs/alpha-vantage-scraper. I believe i have the dependency but i cannot import the class into my program. I have also tried installing the Jar file but that also dint help. Does anyone have any ideas to help? thanks
Here is my pom file:
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.computing</groupId>
<artifactId>ComputingNEA</artifactId>
<version>1.0-SNAPSHOT</version>
<name>ComputingNEA</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>5.8.1</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>11.0.2</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>11.0.2</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-web</artifactId>
<version>11.0.2</version>
</dependency>
<dependency>
<groupId>org.controlsfx</groupId>
<artifactId>controlsfx</artifactId>
<version>11.1.0</version>
</dependency>
<dependency>
<groupId>net.synedra</groupId>
<artifactId>validatorfx</artifactId>
<version>0.1.13</version>
<exclusions>
<exclusion>
<groupId>org.openjfx</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>eu.hansolo</groupId>
<artifactId>tilesfx</artifactId>
<version>11.48</version>
<exclusions>
<exclusion>
<groupId>org.openjfx</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.github.mainstringargs.alphavantagescraper</groupId>
<artifactId>alpha-vantage-scraper</artifactId>
<version>1.5.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
<plugin>
<groupId>org.openjfx</groupId>
<artifactId>javafx-maven-plugin</artifactId>
<version>0.0.8</version>
<executions>
<execution>
<!-- Default configuration for running with: mvn clean javafx:run -->
<id>default-cli</id>
<configuration>
<mainClass>com.computing.computingnea/com.computing.computingnea.Main
</mainClass>
<launcher>app</launcher>
<jlinkZipName>app</jlinkZipName>
<jlinkImageName>app</jlinkImageName>
<noManPages>true</noManPages>
<stripDebug>true</stripDebug>
<noHeaderFiles>true</noHeaderFiles>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Here is the code:
public class ApiData {
public static void main(String[] args) {
String ApiUrl = "alpha-vantage.p.rapidapi.com";
URL url = new URL(ApiUrl);
String apiKey = "14b6cacbe7msh743e555ffddd42dp1";
int timeout = 3000;
AlphaVantageConnector apiConnector = new AlphaVantageConnector(apiKey, timeout);
TimeSeries stockTimeSeries = new TimeSeries(apiConnector);
try {
IntraDay response = stockTimeSeries.intraDay("MSFT", Interval.ONE_MIN, OutputSize.COMPACT);
Map<String, String> metaData = response.getMetaData();
System.out.println("Information: " + metaData.get("1. Information"));
System.out.println("Stock: " + metaData.get("2. Symbol"));
List<StockData> stockData = response.getStockData();
stockData.forEach(stock -> {
System.out.println("date: " + stock.getDateTime());
System.out.println("open: " + stock.getOpen());
System.out.println("high: " + stock.getHigh());
System.out.println("low: " + stock.getLow());
System.out.println("close: " + stock.getClose());
System.out.println("volume: " + stock.getVolume());
});
} catch (AlphaVantageException e) {
System.out.println("something went wrong");
}
}
}
I successfully built this program with mvn clean package. The missing jar alpha-vantage-scraper-1.5.1.jar was downloaded to my local maven repository. The only changes I had to make for the program to actually run was to change String ApiUrl = "alpha-vantage.p.rapidapi.com" to String ApiUrl = "https://alpha-vantage.p.rapidapi.com", and to catch exception MalformedURLException. I made no changes to the pom.
To make it easier for someone else to reproduce this I attach the modified program together with the imports which are not that obvious.
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.List;
import io.github.mainstringargs.alphavantagescraper.AlphaVantageConnector;
import io.github.mainstringargs.alphavantagescraper.TimeSeries;
import io.github.mainstringargs.alphavantagescraper.output.AlphaVantageException;
import io.github.mainstringargs.alphavantagescraper.output.timeseries.IntraDay;
import io.github.mainstringargs.alphavantagescraper.output.timeseries.data.StockData;
import io.github.mainstringargs.alphavantagescraper.input.timeseries.Interval;
import io.github.mainstringargs.alphavantagescraper.input.timeseries.OutputSize;
public class ApiData
{
public static void main(String[] args)
{
String ApiUrl = "https://alpha-vantage.p.rapidapi.com";
try {
URL url = new URL(ApiUrl);
}
catch (MalformedURLException ex) {
System.out.println("bad URL");
}
String apiKey = "14b6cacbe7msh743e555ffddd42dp1";
int timeout = 3000;
AlphaVantageConnector apiConnector = new AlphaVantageConnector(apiKey, timeout);
TimeSeries stockTimeSeries = new TimeSeries(apiConnector);
try {
IntraDay response = stockTimeSeries.intraDay("MSFT", Interval.ONE_MIN, OutputSize.COMPACT);
Map<String, String> metaData = response.getMetaData();
System.out.println("Information: " + metaData.get("1. Information"));
System.out.println("Stock: " + metaData.get("2. Symbol"));
List<StockData> stockData = response.getStockData();
stockData.forEach(stock -> {
System.out.println("date: " + stock.getDateTime());
System.out.println("open: " + stock.getOpen());
System.out.println("high: " + stock.getHigh());
System.out.println("low: " + stock.getLow());
System.out.println("close: " + stock.getClose());
System.out.println("volume: " + stock.getVolume());
});
} catch (AlphaVantageException e) {
System.out.println("something went wrong");
}
}
}
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.
I encounter a
No qualifying bean of type security.oauth2.client.OAuth2AuthorizedClientService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Don't understand what it expected. It's a dependancy.
Here's the LoginController :
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.security.RolesAllowed;
import java.security.Principal;
import java.util.Map;
#RestController
public class LoginController {
private OAuth2AuthorizedClientService authorizedClientService;
public LoginController(OAuth2AuthorizedClientService authorizedClientService) {
this.authorizedClientService = authorizedClientService;
}
#RequestMapping("/**")
#RolesAllowed("USER")
public String getUser(){
return "dashboard";
}
#RequestMapping("/admin")
#RolesAllowed("ADMIN")
public String getAdmin(){
return "Welcome, Admin";
}
#RequestMapping("/*")
public String getUserInfos(Principal activeUser){
StringBuffer userInfos = new StringBuffer();
if (activeUser instanceof UsernamePasswordAuthenticationToken){
userInfos.append(getUsernamePasswordPasswordLoginInfo(activeUser));
} else if (activeUser instanceof OAuth2AuthenticationToken){
userInfos.append(getOAuth2LoginInfo(activeUser));
}
return userInfos.toString();
}
private StringBuffer getOAuth2LoginInfo(Principal activeUser) {
StringBuffer protectedInfo = new StringBuffer();
OAuth2AuthenticationToken authToken = (OAuth2AuthenticationToken) activeUser;
OAuth2User principal = ((OAuth2AuthenticationToken)activeUser).getPrincipal();
OAuth2AuthorizedClient authClient = this.authorizedClientService
.loadAuthorizedClient(authToken.getAuthorizedClientRegistrationId(), authToken.getName());
Map<String, Object> userDetails = ((DefaultOAuth2User) authToken.getPrincipal()).getAttributes();
String userToken = authClient.getAccessToken().getTokenValue();
protectedInfo.append("Welcome, " + userDetails.get("name") + "<br><br>");
protectedInfo.append("email: " + userDetails.get("email") + "<br><br>");
protectedInfo.append("Access Token: " + userToken + "<br><br>");
OidcIdToken idToken = getIdToken(principal);
if(idToken != null){
protectedInfo.append("Token value: " + idToken.getTokenValue() + "<br><br>");
protectedInfo.append("Token mapped values <br><br>");
Map<String, Object> claims = idToken.getClaims();
for (String key : claims.keySet()) {
protectedInfo.append(" " + key + ": " + claims.get(key) + "<br>");
}
}
return protectedInfo;
}
private StringBuffer getUsernamePasswordPasswordLoginInfo(Principal activeUser) {
StringBuffer usernameInfo = new StringBuffer();
UsernamePasswordAuthenticationToken token = ((UsernamePasswordAuthenticationToken) activeUser);
if (token.isAuthenticated()){
User u = (User) token.getPrincipal();
usernameInfo.append("Welcome, " + u.getUsername());
} else {
usernameInfo.append("NA");
}
return usernameInfo;
}
private OidcIdToken getIdToken(OAuth2User principal){
if(principal instanceof DefaultOidcUser) {
DefaultOidcUser oidcUser = (DefaultOidcUser)principal;
return oidcUser.getIdToken();
}
return null;
}
}
Here's the pom.xml... maybe it's a dependancy import problem:
<properties>
<java.version>17</java.version>
<pebble.version>3.1.5</pebble.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<version>2.6.2</version>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>5.1.3</version>
</dependency>
<dependency>
<groupId>io.pebbletemplates</groupId>
<artifactId>pebble-spring-boot-2-starter</artifactId>
<version>3.0.10</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.6.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
Ok.
The problem was the application.properties
The openId was badly configured... it couldn't instanciate the bean... that's what written in the terminal... can't say was crystal clear but was written
I am running below rest API in my code and it gives me the below error. I am not sure whether this is an issue with the jar. Please help me .
java.lang.LinkageError: ClassCastException: attempting to castjar:file:/C:/apache-tomcat-8.5.9/wtpwebapps/searchextractweb/WEB-INF/lib/javax.ws.rs-api-2.0.1.jar!/javax/ws/rs/ext/RuntimeDelegate.class to jar:file:/C:/apache-tomcat-8.5.9/wtpwebapps/searchextractweb/WEB-INF/lib/javax.ws.rs-api-2.0.1.jar!/javax/ws/rs/ext/RuntimeDelegate.class
javax.ws.rs.ext.RuntimeDelegate.findDelegate(RuntimeDelegate.java:146)
javax.ws.rs.ext.RuntimeDelegate.getInstance(RuntimeDelegate.java:120)
javax.ws.rs.core.MediaType.valueOf(MediaType.java:179)
com.sun.jersey.api.client.PartialRequestBuilder.type(PartialRequestBuilder.java:92)
com.sun.jersey.api.client.WebResource.type(WebResource.java:343)
com.tlr.searchextract.workflow.Workflow.retrieveSearchInfo(Workflow.java:1208)
com.tlr.searchextract.workflow.Workflow.createWorkflowRequest(Workflow.java:275)
com.tlr.searchextract.messages.SearchExtractEventHandler.createNewWorkflowRequest(SearchExtractEventHandler.java:675)
com.tlr.searchextract.messages.SearchExtractEventHandler.processRequest(SearchExtractEventHandler.java:134)
com.tlr.searchextract.messages.SearchExtractEventHandler.processMessage(SearchExtractEventHandler.java:65)
com.tlr.searchextract.messages.MessageHandler.routeMessage(MessageHandler.java:92)
com.tlr.searchextract.messages.MessageHandler.processMessages(MessageHandler.java:64)
com.tlr.searchextract.servlet.RequestModel.insertCurrentRequest(RequestModel.java:190)
com.tlr.searchextract.servlet.SEControllerServlet.insertRequestTemplate(SEControllerServlet.java:1344)
com.tlr.searchextract.servlet.SEControllerServlet.performTask(SEControllerServlet.java:1941)
com.tlr.searchextract.servlet.SEControllerServlet.doPost(SEControllerServlet.java:90)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
I have the below code for executing REST API
private void retrieveSearchInfo() {
// find out what type of workflow to create
searchType =
document
.getElementsByTagName("search.type")
.item(0)
.getFirstChild()
.getNodeValue();
try {
excludeMetaDoc =
document
.getElementsByTagName("exclude.metadoc")
.item(0)
.getFirstChild()
.getNodeValue();
} catch (Exception e) {
excludeMetaDoc = "";
}
try {
searchGroup =
document
.getElementsByTagName("search.group")
.item(0)
.getFirstChild()
.getNodeValue();
} catch (Exception e) {
searchGroup = "";
}
try{
imageDoc =
document
.getElementsByTagName("search.imagedoc")
.item(0)
.getFirstChild()
.getNodeValue();
}catch (Exception e) {
imageDoc = "";
}
//add the term "search" to the value of the searchLevel
//vaiable in order to fit the needs of the LTC request
searchLevel =
document
.getElementsByTagName("search.level")
.item(0)
.getFirstChild()
.getNodeValue();
if (searchLevel.equalsIgnoreCase("collection set")) {
searchLevel = "collectionset";
}
//collection or collection set name
searchName =
document
.getElementsByTagName("search.name")
.item(0)
.getFirstChild()
.getNodeValue();
searchNovusVersion =
document
.getElementsByTagName("search.novus.version")
.item(0)
.getFirstChild()
.getNodeValue();
searchNovusEnvironment =
document
.getElementsByTagName("search.novus.environment")
.item(0)
.getFirstChild()
.getNodeValue();
//check to see if the user wants either all of the guids
//for a collection or a collection set
if (searchType.equalsIgnoreCase("all guids")
|| searchType.equalsIgnoreCase("document count")) {
if("Norm".equalsIgnoreCase(searchGroup))
queryText = "=n-relbase";
else
queryText = "=n-document";
queryType = "boolean";
} else {
queryText =
document
.getElementsByTagName("search.query.text")
.item(0)
.getFirstChild()
.getNodeValue();
//escapte special characters
// escape any reserved characters
// Problem using an ampersand (&) in the Search query. Maestro translates it to an entity in the relevant data. Need to use the word "and".
queryText = escapeXML(queryText, "&", "and");
// queryText = escapeXML(queryText, "&", "&");
queryText = escapeXML(queryText, "<", "<");
queryText = escapeXML(queryText, ">", ">");
queryText = escapeXML(queryText, "'", "'");
queryText = escapeXML(queryText, "\"", """);
//find the search type boolean or natural
queryType =
document
.getElementsByTagName("search.query.type")
.item(0)
.getFirstChild()
.getNodeValue();
}
try {
searchOutputResource =
document
.getElementsByTagName("search.output.resource")
.item(0)
.getFirstChild()
.getNodeValue();
searchOutputPath =
document
.getElementsByTagName("search.output.path")
.item(0)
.getFirstChild()
.getNodeValue();
searchOutputPrefix =
document
.getElementsByTagName("search.output.file.prefix")
.item(0)
.getFirstChild()
.getNodeValue();
} catch (Exception e) {
searchOutputResource = "";
searchOutputPath = "";
searchOutputPrefix = "";
if (searchOutputPrefix != null) {
if (searchOutputPrefix.length() == 0) {
searchOutputPrefix = "se";
}
} else {
searchOutputPrefix = "se";
}
//e.printStackTrace();
}
//now get the resource signon and password
String output="";
try {
Client client = Client.create();
System.out.println("resourceName: "+searchOutputResource);
WebResource webResource = client.resource("http://localhost:8080/searchextract/webapi/resource?isGroupAndResource=true&groupId="
+ requestGroup + "&resourceName=" + searchOutputResource);
ClientResponse response = webResource.type("application/json").get(ClientResponse.class);
if (response.getStatus() != 200)
{
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
output = response.getEntity(String.class);
ResultSetIterator rsi = new ResultSetIterator(output);
searchOutputResourceUser = rsi.getFieldValue("resource_signon");
searchOutputResourcePass = rsi.getFieldValue("resource_password");
} catch (RemoteException re) {
System.err.println(re.detail.getMessage());
if (re.detail.getMessage().indexOf("DuplicateKeyException") > -1) {
//throw new Exception("Duplicate record");
}
} catch (NamingException e) {
System.err.println("NamingException: " + e.getMessage());
System.err.println("Root cause: " + e.getRootCause());
System.err.println("Explanation: " + e.getExplanation());
}
catch (Exception e) {
System.err.println(e.getMessage());
}
}
Below is the pom.xml file
<?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>
<parent>
<groupId>com.tlr.searchextractproject</groupId>
<artifactId>parent-project</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<groupId>com.tlr.searchextractproject</groupId>
<artifactId>searchextract</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>searchextract</name>
<properties>
<jersey.version>2.16</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.16</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-bundle -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.16</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.16</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.ws.rs/jsr311-api -->
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.owlike</groupId>
<artifactId>genson</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<!-- use the following artifactId if you don't need servlet 2.x compatibility -->
<!-- artifactId>jersey-container-servlet</artifactId -->
</dependency>
<dependency>
<groupId>org.glassfish.jersey.bundles.repackaged</groupId>
<artifactId>jersey-guava</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.16</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.9.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.9.1</version>
</dependency>
<!-- uncomment this to get JSON support -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.11.1</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-dbcp</artifactId>
<version>8.5.9</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
<version>8.5.9</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-coyote</artifactId>
<version>8.5.9</version>
</dependency>
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.11.0.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<version>1.4.01</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.ibm</groupId>
<artifactId>com.ibm.mq</artifactId>
<version>6.0.2.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.ibm/com.ibm.mqjms -->
<dependency>
<groupId>com.ibm</groupId>
<artifactId>com.ibm.mqjms</artifactId>
<version>6.0.2.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.resource/connector -->
<dependency>
<groupId>javax.resource </groupId>
<artifactId>connector</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>com.ibm</groupId>
<artifactId>com.ibm.dhbcore </artifactId>
<version>7.1.0.0</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<finalName>searchextract</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<inherited>true</inherited>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
This exception is thrown while executing the below line
ClientResponse response = webResource.type("application/json").get(ClientResponse.class)
I am using Java 8 and Tomcat 8
I have faced the same error with my code and could resolve by using jersey dependency version 2.34
POM dependency
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
<version>3.0.0</version>
</dependency>
My Error Message
2021-09-22 08:32:23.839 INFO 10 --- [http-nio-9070-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler dispatch failed; nested exception is java.lang.LinkageError: ClassCastException: attempting to castjar:file:/faw-qa-api/target/faw-qa-api-1.0-SNAPSHOT.jar!/javax/ws/rs/client/ClientBuilder.class to jar:file:/faw-qa-api/target/faw-qa-api-1.0-SNAPSHOT.jar!/javax/ws/rs/client/ClientBuilder.class] with root cause
java.lang.LinkageError: ClassCastException: attempting to castjar:file:/faw-qa-api/target/faw-qa-api-1.0-SNAPSHOT.jar!/javax/ws/rs/client/ClientBuilder.class to jar:file:/faw-qa-api/target/faw-qa-api-1.0-SNAPSHOT.jar!/javax/ws/rs/client/ClientBuilder.class
at javax.ws.rs.client.ClientBuilder.newBuilder(ClientBuilder.java:105)
I updated the dependency version of jersey-client and jersey-common to 2.34 and the issue was resolved.
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.34</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
<version>2.34</version>
</dependency>
cant solve this exception
java.lang.NoSuchMethodError: org.springframework.dao.support.DataAccessUtils.nullableSingleResult(Ljava/util/Collection;)Ljava/lang/Object;
String sql = "SELECT uname FROM USER_DATA WHERE uid=? AND upass=?";
try {
System.out.println("2222222222222");
String userId = jdbcTemplate.queryForObject(sql, new Object[] {
user.getUserId(), user.getPassword() }, String.class);System.out.println("noooooo");
return userId;
} catch (Exception e) {
e.printStackTrace();
return null;
}
my versions
spring-boot-starter-parent 1.5.10.RELEASE,spring-boot-starter jdbc,
spring-boot-starter-web,spring-boot-starter-test,spring-boot-starter-tomcat
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<dependency>
<groupId>org.eclipse.jdt.core.compiler</groupId>
<artifactId>ecj</artifactId>
<version>4.6.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
About lines are in pom which all need to change kindly help