Google API for Plus Builder getting failed - java

I am trying to get people information from the google API.
Below is the code
public static void main(String[] args) throws IOException, JSONException
{
plus = new Plus.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("youtubeSearchSample").build();
Person profile = plus.people().get("https://www.googleapis.com/plus/v1/people/118359906569721392650?key=<Key>").execute();
System.out.println("hello-->"+profile.toPrettyString());
}
public static Credential authorize(List<String> scopes, String credentialDatastore) throws IOException {
// Load client secrets.
InputStreamReader clientSecretReader = new InputStreamReader(Auth.class.getResourceAsStream("/client_secrets.json"));
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretReader);
// Checks that the defaults have been replaced (Default = "Enter X here").
if (clientSecrets.getDetails().getClientId().startsWith("Enter")
|| clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
System.out.println(
"Enter Client ID and Secret from https://code.google.com/apis/console/?api=youtube"
+ "into src/main/resources/client_secrets.json");
System.exit(1);
}
// This creates the credentials datastore at ~/.oauth-credentials/${credentialDatastore}
FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(System.getProperty("user.home") + "/" + CREDENTIALS_DIRECTORY));
DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore(credentialDatastore);
System.out.println("scopes-->"+scopes.toString());
System.out.println("clientSecrets-->"+clientSecrets.toString());
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialDataStore(datastore)
.build();
// Build the local server and bind it to port 8080
LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();
// Authorize.
return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
}
When I try to run the above code I am getting the following exception.
Exception in thread "main" java.lang.NoSuchMethodError: com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.<init>(Lcom/google/api/client/http/HttpTransport;Lcom/google/api/client/http/HttpRequestInitializer;Ljava/lang/String;Ljava/lang/String;Lcom/google/api/client/json/JsonObjectParser;Lcom/google/api/client/googleapis/services/GoogleClientRequestInitializer;Ljava/lang/String;Z)V
at com.google.api.services.plus.Plus.<init>(Plus.java:134)
at com.google.api.services.plus.Plus$Builder.build(Plus.java:2086)
at com.google.youtube.search.GoogleUserDetails.main(GoogleUserDetails.java:32)
Where as the same I tried for YouTube.Builder it worked fine.
Below is the sample code which I use to for youtube builder.
youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new
HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("youtubeSearchSample").build();
Here I just replaced the YouTube.Builder with Plus.Builder but I got the above exception which mentioned as above.
Any GoogleAPI experts let me where I made a mistake.
Pom.xml dependencies:
<dependencies>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-youtube</artifactId>
<version>${project.youtube.version}</version>
</dependency>
<!-- Required for any code that makes calls to the Google Analytics API -->
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-youtubeAnalytics</artifactId>
<version>${project.youtube.analytics.version}</version>
</dependency>
<!-- This dependency is only used for the Topics API sample, which requires
the Jackson JSON parser -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-jackson2</artifactId>
<version>${project.http.version}</version>
</dependency>
<dependency>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client-jetty</artifactId>
<version>${project.oauth.version}</version>
</dependency>
<dependency>
<groupId>com.google.collections</groupId>
<artifactId>google-collections</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
<!-- Google API dependency -->
<dependency>
<groupId>com.googlecode.googleplus</groupId>
<artifactId>google-plus-java-api</artifactId>
<version>0.0.3</version>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-plus</artifactId>
<version>v1-rev64-1.13.2-beta</version>
</dependency>
</dependencies>

I've fixed this error by updating version of api library in pom.xml.
Then you should call
mvn clean package
Latest versions of google libraries you can find in Maven repository:
http://mvnrepository.com/artifact/com.googlecode.googleplus/google-plus-java-api

Related

Quarkus - could not find writer for content-type application/x-www-form-urlencoded type

This is my code for doing a request with jax-rs Client:
private Client client;
private static final int TIMEOUT = 8000;
#PostConstruct
public void init() {
client = ClientBuilder.newBuilder()
.readTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
.connectTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
.build();
}
....
final String resource = "/some-endpoint/{id}/securityinfo";
final String path = url + resource;
final WebTarget target = client
.target(path)
.resolveTemplate("id", email);
final var form = new Form().param("mail", email);
final Response response = target
.request()
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED));
if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
throw new MyException(response.readEntity(String.class));
}
I receive the error:
javax.ws.rs.ProcessingException: RESTEASY004655: Unable to invoke request: javax.ws.rs.ProcessingException: RESTEASY003215: could not find writer for content-type application/x-www-form-urlencoded type: javax.ws.rs.core.Form
This happens only with form - content type request, as the json support works properly.
EDIT
These are the dependencies used:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-orm</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-rest-client</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-rest-client-jackson</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-jdbc-oracle</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-arc</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-jsonb</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5</artifactId>
<scope>test</scope>
</dependency>
Have you tried using (https://docs.oracle.com/javaee/7/api/javax/ws/rs/client/Entity.html#form-javax.ws.rs.core.Form-) :
Entity.form(form);
I'm not sure it will fix the issue as it is just shorthand for what you have. But i would give it a try.
In order to find a solution easier can you share the dependencies you are using on your project.

NoClassDefFoundError in Azure Function App for Digital Twin

I am developing an azure function app. function in azure function app is responsible to receive messages from azure event hub. this method should should update azure digital twin. I am creating Azure DigitalTwin instance like below
#FunctionName("eventGridMonitorString")
public void eventHubProcessor(
#EventHubTrigger(name = "msg", eventHubName = "", connection = "EventHubConnectionString") String message,
final ExecutionContext context) {
// context.getLogger().info(message);
String adtUrl = System.getenv("ADT_SERVICE_URL");
context.getLogger().info("ADTURl : " + adtUrl);
DigitalTwinsClient client = new DigitalTwinsClientBuilder().credential(new ClientSecretCredentialBuilder()
.tenantId("my_tenant_id").clientId("my_client_id")
.clientSecret("my_client_secret").build()).endpoint(adtUrl).buildClient();
Iterable<DigitalTwinsModelData> modelList = client.listModels();
Iterator<DigitalTwinsModelData> it = modelList.iterator();
while (it.hasNext()) {
DigitalTwinsModelData model = it.next();
context.getLogger().info("" + model.getDtdlModel());
}
for (DigitalTwinsModelData model : modelList) {
context.getLogger().info("Created model: " + model.getModelId());
}
}
This code works fine in my local java application but when I deploy this code to azure function app, it gives me below error
2021-05-27T07:42:35.173 [Error] Executed 'Functions.eventGridMonitorString' (Failed, Id=12a87102-78a3-4e2e-8715-b4401091d753, Duration=116ms)Result: FailureException: NoClassDefFoundError: Could not initialize class reactor.netty.http.client.HttpClientConfigStack: java.lang.reflect.InvocationTargetExceptionat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)at java.lang.reflect.Method.invoke(Method.java:498)at com.microsoft.azure.functions.worker.broker.JavaMethodInvokeInfo.invoke(JavaMethodInvokeInfo.java:22)at com.microsoft.azure.functions.worker.broker.JavaMethodExecutorImpl.execute(JavaMethodExecutorImpl.java:54)at com.microsoft.azure.functions.worker.broker.JavaFunctionBroker.invokeMethod(JavaFunctionBroker.java:57)at com.microsoft.azure.functions.worker.handler.InvocationRequestHandler.execute(InvocationRequestHandler.java:33)at com.microsoft.azure.functions.worker.handler.InvocationRequestHandler.execute(InvocationRequestHandler.java:10)at com.microsoft.azure.functions.worker.handler.MessageHandler.handle(MessageHandler.java:45)at com.microsoft.azure.functions.worker.JavaWorkerClient$StreamingMessagePeer.lambda$onNext$0(JavaWorkerClient.java:92)at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)at java.util.concurrent.FutureTask.run(FutureTask.java:266)at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)at java.lang.Thread.run(Thread.java:748)Caused by: java.lang.NoClassDefFoundError: Could not initialize class reactor.netty.http.client.HttpClientConfigat reactor.netty.http.client.HttpClientConnect.<init>(HttpClientConnect.java:84)at reactor.netty.http.client.HttpClient.create(HttpClient.java:393)at com.azure.core.http.netty.NettyAsyncHttpClientBuilder.build(NettyAsyncHttpClientBuilder.java:91)at com.azure.core.http.netty.implementation.ReactorNettyClientProvider.createInstance(ReactorNettyClientProvider.java:14)at com.azure.core.implementation.http.HttpClientProviders.createInstance(HttpClientProviders.java:58)at com.azure.core.http.HttpClient.createDefault(HttpClient.java:50)at com.azure.core.http.HttpClient.createDefault(HttpClient.java:40)at com.azure.core.http.HttpPipelineBuilder.build(HttpPipelineBuilder.java:62)at com.azure.digitaltwins.core.DigitalTwinsClientBuilder.buildPipeline(DigitalTwinsClientBuilder.java:151)at com.azure.digitaltwins.core.DigitalTwinsClientBuilder.buildAsyncClient(DigitalTwinsClientBuilder.java:193)at com.azure.digitaltwins.core.DigitalTwinsClientBuilder.buildClient(DigitalTwinsClientBuilder.java:160)at com.ey.azurefunctions.PolarDelightFunctionApp.Function.eventHubProcessor(Function.java:32)... 16 more
am I missing something or is there any issue with above code?
Edit 1 I have below maven dependencies added to my project
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-digitaltwins-core</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-core-http-netty</artifactId>
<version>1.7.1</version> <!-- {x-version-update;com.azure:azure-core-http-netty;dependency} -->
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.49.Final</version>
</dependency>
<dependency>
<groupId>io.projectreactor.netty</groupId>
<artifactId>reactor-netty</artifactId>
<version>1.0.7</version>
</dependency>
<dependency>
<groupId>io.projectreactor.netty</groupId>
<artifactId>reactor-netty-http</artifactId>
<version>1.0.7</version>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-bom</artifactId>
<version>Dysprosium-SR20</version>
<type>pom</type>
</dependency>

An attempt was made to call a method that does not exist. STS

When i run the STS(SpringBoot) application i get the below error:
The attempt was made from the following location: org.apache.catalina.authenticator.AuthenticatorBase.startInternal(AuthenticatorBase.java:1321)
The following method did not exist:
javax.servlet.ServletContext.getVirtualServerName()Ljava/lang/String;
The method's class, javax.servlet.ServletContext, is available from the following locations:
jar:file:/home/talha/.m2/repository/javax/servlet/servlet-api/2.5/servlet-api-2.5.jar!/javax/servlet/ServletContext.class
jar:file:/home/talha/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/9.0.33/tomcat-embed-core-9.0.33.jar!/javax/servlet/ServletContext.class
It was loaded from the following location:
file:/home/talha/.m2/repository/javax/servlet/servlet-api/2.5/servlet-api-2.5.jar
The suggestion in the ide is:
Action:
Correct the classpath of your application so that it contains a single, compatible version of javax.servlet.ServletContext
I guess there is something wrong with my pom.xml the code is as below:
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.uni</groupId>
<artifactId>authorize</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>authorize</name>
<description>API for user registration and login with validation</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail -->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-mongodb -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/joda-time/joda-time -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>com.googlecode.jsontoken</groupId>
<artifactId>jsontoken</artifactId>
<version>1.0</version>
</dependency>
<!-- Thanks for using https://jar-download.com -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<finalName>authrize</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
The main dependencies causing the error are:
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>com.googlecode.jsontoken</groupId>
<artifactId>jsontoken</artifactId>
<version>1.0</version>
</dependency>
I get the error only after adding the above dependencies, the need to add the dependencies is the below class:
package com.uni.authorize.service;
import java.security.InvalidKeyException;
import java.security.SignatureException;
import java.util.List;
import org.joda.time.DateTime;
import org.joda.time.Instant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import com.google.gson.JsonObject;
import com.uni.authorize.model.TokenKeys;
import com.uni.authorize.pojo.TokenObject;
import com.uni.authorize.repository.TokenKeysRepository;
import com.uni.authorize.service.CreateToken;
import net.oauth.jsontoken.JsonToken;
import net.oauth.jsontoken.crypto.HmacSHA256Signer;
#Configuration
public class CreateToken {
private static final Logger LOGGER = LoggerFactory.getLogger(CreateToken.class);
private static final String ISSUER = "UnI United Tech";
#Autowired
TokenKeysRepository tokenKeyRepository;
public TokenObject createToken(String userId) {
List<TokenKeys> tokenList = tokenKeyRepository.findAll();
TokenKeys tokenKeys = tokenList.get(0);
long accessTokenValidity = tokenKeys.getAccessTokenValidity();
long refreshTokenValidiry = tokenKeys.getRefreshTokenValidity();
String accessTokenKey = tokenKeys.getAccessKey();
String refreshTokenKey = tokenKeys.getRefreshKey();
String accessToken = generateAccessToken(userId, accessTokenKey, accessTokenValidity);
String refreshToken = generateRefreshToken(userId, refreshTokenKey, refreshTokenValidiry);
TokenObject tokenObject = new TokenObject();
tokenObject.setAccess_token(accessToken);
tokenObject.setRefresh_token(refreshToken);
tokenObject.setToken_type("bearer");
tokenObject.setExpires_in(accessTokenValidity);
tokenObject.setScope("read write trust");
return tokenObject;
}
private String generateAccessToken(String userId, String accessTokenKey, long accessTokenValidity) {
HmacSHA256Signer signer;
try {
signer = new HmacSHA256Signer(ISSUER, null, accessTokenKey.getBytes());
} catch (InvalidKeyException e) {
throw new RuntimeException(e);
}
// Configure JSON token
JsonToken token = new net.oauth.jsontoken.JsonToken(signer);
// token.setAudience(AUDIENCE);
DateTime dateTime = new DateTime();
long dateTimeMillis = dateTime.getMillis();
// DateTime currentTimeDateTime = new DateTime(dateTimeMillis);
// DateTime expiryTimeDateTime = new DateTime(dateTimeMillis + accessTokenValidity);
Instant currentTimeInstant = new org.joda.time.Instant(dateTimeMillis);
Instant expirationTimeInstant = new org.joda.time.Instant(dateTimeMillis + accessTokenValidity);
LOGGER.debug("Current Time Instant" + currentTimeInstant);
LOGGER.debug("Expiration Tine Instant" + expirationTimeInstant);
token.setIssuedAt(currentTimeInstant);
token.setExpiration(expirationTimeInstant);
// Configure request object, which provides information of the item
JsonObject request = new JsonObject();
request.addProperty("userId", userId);
JsonObject payload = token.getPayloadAsJsonObject();
payload.add("info", request);
try {
return token.serializeAndSign();
} catch (SignatureException e) {
throw new RuntimeException(e);
}
}
private String generateRefreshToken(String userId, String refreshTokenKey, long refreshTokenValidiry) {
HmacSHA256Signer signer;
try {
signer = new HmacSHA256Signer(ISSUER, null, refreshTokenKey.getBytes());
} catch (InvalidKeyException e) {
throw new RuntimeException(e);
}
// Configure JSON token
JsonToken token = new net.oauth.jsontoken.JsonToken(signer);
// token.setAudience(AUDIENCE);
DateTime dateTime = new DateTime();
long dateTimeMillis = dateTime.getMillis();
// DateTime currentTimeDateTime = new DateTime(dateTimeMillis);
// DateTime expiryTimeDateTime = new DateTime(dateTimeMillis + refreshTokenValidiry);
Instant currentTimeInstant = new org.joda.time.Instant(dateTimeMillis);
Instant expirationTimeInstant = new org.joda.time.Instant(dateTimeMillis + refreshTokenValidiry);
LOGGER.debug("Current Time Instant" + currentTimeInstant);
LOGGER.debug("Expiration Tine Instant" + expirationTimeInstant);
token.setIssuedAt(currentTimeInstant);
token.setExpiration(expirationTimeInstant);
// Configure request object, which provides information of the item
JsonObject request = new JsonObject();
request.addProperty("userId", userId);
JsonObject payload = token.getPayloadAsJsonObject();
payload.add("info", request);
try {
return token.serializeAndSign();
} catch (SignatureException e) {
throw new RuntimeException(e);
}
}
}
Please help me resolve this issue.
Thanks in advance
getVirtualServerName() was added in Servlet 3.1, but you included servlet-api-2.5.jar is your application.
Options:
Change your dependencies to include servlet-api-3.1.jar (or later)
Remove the servlet-api-2.5.jar dependency, since the correct version is included in the Embedded Tomcat file (tomcat-embed-core-9.0.33.jar).
Actually, you should never ship servlet-api.jar with your application, since it will be provided by the Servlet Container. Seems you're missing <scope>provided</scope> in your dependency tag for the servlet-api file.
I solved a similar issue by adding dependencyManagement.
Here is an example of my code where a version of org.springframework.cloud was the problem:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2021.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

NoClassDefFoundError While Using Java Web Tokens

I am trying to understand the usage of java web tokens so I wanted to made a simple web application. I just create a simple login system which uses jwt but I got java.lang.NoClassDefFoundError: io/jsonwebtoken/Jwts in some point. Here is my related codes:
Connect.java:
#WebServlet("/Connect")
public class Connect extends HttpServlet {
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
String username = req.getParameter("username");
String password = req.getParameter("password");
Jjwt jjwt = new Jjwt();
jjwt.authorize(username, password);
if(jjwt.flag == true){
DatabaseInteractions databaseInteractions = new DatabaseInteractions();
JsonOutput output = databaseInteractions.getAccountDetails(databaseInteractions.getID(username));
ServletContext context = getServletContext();
req.setAttribute("username", username);
req.setAttribute("btcAmount", output.getBtcAmount());
req.setAttribute("ethAmount", output.getEthAmount());
req.setAttribute("xrpAmount", output.getXrpAmount());
req.setAttribute("trxAmount", output.getTrxAmount());
req.setAttribute("adaAmount", output.getAdaAmount());
context.getRequestDispatcher("/Home.jsp").forward(req, resp);
}
}
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
}
}
Jjwt.java:
public class Jjwt{
public boolean flag;
public Jjwt(){
flag = false;
}
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response authorize(String username, String password){
DatabaseInteractions databaseInteractions = new DatabaseInteractions();
if(databaseInteractions.connectToDatabase() == false){
System.out.println("Error: Could not connect to database. Please try later ...");
return Response.status(Response.Status.UNAUTHORIZED).build();
}
if(databaseInteractions.login(username, password)){
String key = "key";
long time = System.currentTimeMillis();
String jwt = Jwts.builder()
.signWith(SignatureAlgorithm.HS256, key)
.setSubject(username)
.setIssuedAt(new Date(time))
.setExpiration(new Date(time+9000))
.claim("password",password)
.compact();
JsonObject jsonObject = Json.createObjectBuilder().add("JWT", jwt).build();
flag = true;
return Response.status(Response.Status.CREATED).entity(jsonObject).build();
}else{
return Response.status(Response.Status.UNAUTHORIZED).build();
}
}
}
In String jwt = Jwts.builder() point at Jjwt.java class, I got the error that I mentioned above. I added all the necessary dependencies I guess, here is my pom.xml(By the way, this is a Maven project):
<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>
<repository>
<id>maven-repository.java.net</id>
<name>Java.net Maven 1 Repository (legacy)</name>
<url>http://download.java.net/maven/1</url>
<layout>legacy</layout>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.9</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
<version>8.5.27</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.1-m09</version>
</dependency>
<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
</dependencies>
Where am I doing wrong?
Edit: When I add the below dependencies:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.9</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.9</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.9</version>
</dependency>
Now it gives java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonProcessingException at the same point.

Lucene exception NoSuchMethodError with version 6.4.0

I am relatively new to Lucene and playing with the latest version 6.4.0.
I have written a cutom analyzer class for doing synonyms,
public class MySynonymAnalyzer extends Analyzer {
#Override
protected TokenStreamComponents createComponents(String fieldName) {
Tokenizer source = new ClassicTokenizer();
TokenStream filter = new StandardFilter(source);
filter = new LowerCaseFilter(filter);
filter = new SynonymGraphFilter(filter, getSynonymsMap(), false);
filter = new FlattenGraphFilter(filter);
return new TokenStreamComponents(source, filter);
}
private SynonymMap getSynonymsMap() {
try {
SynonymMap.Builder builder = new SynonymMap.Builder(true);
builder.add(new CharsRef("work"), new CharsRef("labor"), true);
builder.add(new CharsRef("work"), new CharsRef("effort"), true);
SynonymMap mySynonymMap = builder.build();
return mySynonymMap;
} catch (Exception ex) {
return null;
}
}
In the line where I call getSynonymsMap(), I get the following exception:
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.lucene.util.UnicodeUtil.UTF16toUTF8WithHash([CIILorg/apache/lucene/util/BytesRef;)I
at org.apache.lucene.analysis.synonym.SynonymMap$Builder.add(SynonymMap.java:192)
at org.apache.lucene.analysis.synonym.SynonymMap$Builder.add(SynonymMap.java:239)
at m2_lab4.MySynonymAnalyzer.getSynonymsMap(MySynonymAnalyzer.java:37)
at m2_lab4.MySynonymAnalyzer.createComponents(MySynonymAnalyzer.java:28)
at org.apache.lucene.analysis.Analyzer.tokenStream(Analyzer.java:162)
at org.apache.lucene.document.Field.tokenStream(Field.java:568)
Version 6.4.0 doesn't seem to have method UTF16toUTF8WithHash in class UnicodeUtil. I am using everything from lucene 6.4.0 and there doesn't seem to be any old versioned jar in my classpath. This is how my maven dependendies look like:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<lucene.version>6.4.0</lucene.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
<version>${lucene.version}</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analyzers-common</artifactId>
<version>${lucene.version}</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-queryparser</artifactId>
<version>${lucene.version}</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-queries</artifactId>
<version>${lucene.version}</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analyzers</artifactId>
<version>3.6.2</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-facet</artifactId>
<version>${lucene.version}</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-spatial</artifactId>
<version>${lucene.version}</version>
</dependency>
<dependency>
<groupId>com.spatial4j</groupId>
<artifactId>spatial4j</artifactId>
<version>0.4.1</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
Any idea what's going on? I am specially puzzled by the [CIILorg/apache/lucene/util/BytesRef text inside the exception description.

Categories