Class not found in Java Servlet using Maven - java

I tried to import the Gson library from Google using Maven but when I run my web application, I receive error that the Gson class isn't found. I tried to put provided for the scope of the Gson library but it didn't do anything.
pom.xml
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>groupId</groupId>
<artifactId>Skeleton</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
TestServlet.java
package servlets;
import com.google.gson.Gson;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Philippe on 2016-05-10.
*/
#WebServlet(name = "/TestServlet")
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<String> list = new ArrayList<String>() ;
list.add("item1");
list.add("item2");
Gson gson = new Gson() ;
String json = gson.toJson(list) ;
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
}
log
java.lang.ClassNotFoundException: com.google.gson.Gson at
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1305)
at
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1139)
at servlets.TestServlet.doGet(TestServlet.java:34) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:622) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
Is there anything I'm missing ?

Just try by removing <scope>compile</scope> as documented in the site.
<!-- http://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>

Related

Connecting Selenium Test to AWS Desktop Browser through cooperate proxy

I am trying to connect to the AWS device farm for desktop browser testing with Selenium 4 through a cooperate proxy, with no luck.
Here is the code I am using:
pom.xml
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>My Selenium Tests</groupId>
<artifactId>Selenium</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bom</artifactId>
<version>2.17.209</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- TestNG -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.6.0</version>
<scope>compile</scope>
</dependency>
<!-- AWS -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>apache-client</artifactId>
<version>2.17.209</version>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>devicefarm</artifactId>
<version>2.17.209</version>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>aws-sdk-java</artifactId>
<version>2.17.209</version>
</dependency>
<!-- Selenium -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.2.2</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-remote-driver</artifactId>
<version>4.2.2</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.10.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
</project>
SeleniumTest.java
package Selenium;
import okhttp3.*;
import okhttp3.Authenticator;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.remote.HttpCommandExecutor;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.http.ClientConfig;
import org.openqa.selenium.remote.http.HttpClient;
import org.openqa.selenium.remote.http.HttpClient.Factory;
import org.testng.annotations.Test;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.http.apache.ProxyConfiguration;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.devicefarm.DeviceFarmClient;
import software.amazon.awssdk.services.devicefarm.model.CreateTestGridUrlRequest;
import software.amazon.awssdk.services.devicefarm.model.CreateTestGridUrlResponse;
import java.io.IOException;
import java.net.*;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
public class SeleniumTest {
#Test
public void search() throws MalformedURLException, URISyntaxException, UnknownHostException {
ProxyConfiguration.Builder proxyConfiguration = ProxyConfiguration.builder();
proxyConfiguration.endpoint(new URI("http://myProxyUrl:8080"));
proxyConfiguration.username("myProxyUsername");
proxyConfiguration.password("myProxyPassword");
ApacheHttpClient.Builder httpClientBuilder = ApacheHttpClient.builder().proxyConfiguration(proxyConfiguration.build());
String projectARN = "arn:aws:devicefarm:someString:testgrid-project:someUid";
DeviceFarmClient deviceFarmClient = DeviceFarmClient.builder()
.credentialsProvider(DefaultCredentialsProvider.create())
.httpClientBuilder(httpClientBuilder)
.overrideConfiguration(ClientOverrideConfiguration.builder().build())
.region(Region.US_WEST_2)
.build();
CreateTestGridUrlRequest testGridUrlrequest = CreateTestGridUrlRequest.builder()
.expiresInSeconds(300)
.projectArn(projectARN)
.build();
CreateTestGridUrlResponse response = deviceFarmClient.createTestGridUrl(testGridUrlrequest);
URL testGridUrl = new URL(response.url());
Authenticator proxyAuthenticator = new Authenticator() {
public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic("myProxyUsername", "myProxyPassword");
return response.request().newBuilder()
.header("Proxy-Authorization", credential)
.build();
}
};
Builder okHttpClientBuilder = new Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("myProxyUrl", 8080)))
.proxyAuthenticator(proxyAuthenticator);
FirefoxOptions browserOptions = new FirefoxOptions();
browserOptions.addPreference("network.proxy.type", 0);
Factory factory = new MyHttpClientFactory(new OkHttpClient(okHttpClientBuilder));
HttpCommandExecutor executor = new HttpCommandExecutor(new HashMap<>(), testGridUrl, factory);
RemoteWebDriver remoteWebDriver = new RemoteWebDriver(executor, browserOptions);
remoteWebDriver.navigate().to("https://www.google.de");
remoteWebDriver.quit();
}
public class MyHttpClientFactory implements HttpClient.Factory {
final OkHttpClient okHttpClient;
public MyHttpClientFactory(OkHttpClient okHttpClient) {
this.okHttpClient = okHttpClient;
}
#Override
public HttpClient createClient(URL url) {
return (HttpClient) okHttpClient;
}
#Override
public HttpClient createClient(ClientConfig config) {
return (HttpClient) okHttpClient;
}
#Override
public void cleanupIdleClients() {
}
}
}
As you can see, I used the ApacheHttpClient as HTTPClient for the AWS DeviceFarmClient, so I can authenticate with the cooperate proxy - which works like a charm. I get the testGridUrl, which I can use in the second step to send commands via the RemoteWebDriver to the AWS Desktop Browser.
This is where the problems start. I use the OkHttpClient (recommended by Selenium) as HTTPClient for the RemoteWebDriver - here also to enable proxy authentication (which I think is not possible with the built in HTTPClient).
But when the test is run, I get a class cast exception - it seems the okHttpCLient cannot be cast to HttpClient.
java.lang.ClassCastException: class okhttp3.OkHttpClient cannot be cast to class org.openqa.selenium.remote.http.HttpClient (okhttp3.OkHttpClient and org.openqa.selenium.remote.http.HttpClient are in unnamed module of loader 'app')
at Selenium.SeleniumTest$MyHttpClientFactory.createClient(SeleniumTest.java:103)
at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:107)
at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:94)
at Selenium.SeleniumTest.search(SeleniumTest.java:77)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.testng.internal.invokers.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:139)
at org.testng.internal.invokers.TestInvoker.invokeMethod(TestInvoker.java:677)
at org.testng.internal.invokers.TestInvoker.invokeTestMethod(TestInvoker.java:221)
at org.testng.internal.invokers.MethodRunner.runInSequence(MethodRunner.java:50)
at org.testng.internal.invokers.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:962)
at org.testng.internal.invokers.TestInvoker.invokeTestMethods(TestInvoker.java:194)
at org.testng.internal.invokers.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:148)
at org.testng.internal.invokers.TestMethodWorker.run(TestMethodWorker.java:128)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
at org.testng.TestRunner.privateRun(TestRunner.java:806)
at org.testng.TestRunner.run(TestRunner.java:601)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:433)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:427)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:387)
at org.testng.SuiteRunner.run(SuiteRunner.java:330)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:95)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1256)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1176)
at org.testng.TestNG.runSuites(TestNG.java:1099)
at org.testng.TestNG.run(TestNG.java:1067)
Did anyone use a proxy for connection to the AWS DeviceFarm before with Selenium 4 and can give me some hints on how to procede (replace the HTTPClient? Cast possible?)
All the best, Pita.

The method extractAll(String) is undefined for the type ZipFile with zip4j

I'm trying to make a program which unzips then parses the xml file in xml.zip.
Adding the dependency for zip4j, this 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>interview</groupId>
<artifactId>programES</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>xmlToES</name>
<dependencies>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-xml -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.12.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</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.12.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.lingala.zip4j/zip4j -->
<dependency>
<groupId>net.lingala.zip4j</groupId>
<artifactId>zip4j</artifactId>
<version>2.6.4</version>
</dependency>
</dependencies>
</project>
My code for the parser :
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import model.Products;
import net.lingala.zip4j.core.ZipFile;
import org.apache.commons.lang3.StringUtils;
import java.util.zip.ZipFile;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Parser {
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new XmlMapper();
String source = "C:\\Users\\user\\java_program\\xml.zip";
String destination = "C:\\Users\\user\\java_program\\xml";
ZipFile zipFile = new ZipFile(source);
zipFile.extractAll(destination);
//Reads from XML and converts to POJO
Products products = objectMapper.readValue(
StringUtils.toEncodedString(Files.readAllBytes(Paths.get("C:\\Users\\user\\java_program\\xml\\xml.xml")), StandardCharsets.UTF_8), Products.class);
System.out.println(products);
}
}
The program still write an error : The method extractAll(String) is undefined for the type ZipFile
any help is really appreciated
You should import net.lingala.zip4j.core.ZipFile instead of java.util.zip.Zipfile
delete the line:
import java.util.zip.ZipFile;
and delete
.core from your import import net.lingala.zip4j.core.ZipFile;
Whole class:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import model.Products;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import org.apache.commons.lang3.StringUtils;
public class Parser {
public static void main(String[] args) throws IOException, ZipException {
ObjectMapper objectMapper = new XmlMapper();
String source = "C:\\Users\\user\\java_program\\xml.zip";
String destination = "C:\\Users\\user\\java_program\\xml";
ZipFile zipFile = new ZipFile(source);
zipFile.extractAll(destination);
//Reads from XML and converts to POJO
Products products = objectMapper.readValue(
StringUtils.toEncodedString(Files.readAllBytes(Paths.get("C:\\Users\\user\\java_program\\xml\\xml.xml")), StandardCharsets.UTF_8), Products.class);
System.out.println(products);
}
}
In your imports you are importing java.util.Zipfile so remove -
import java.util.zip.ZipFile;
and it should work.

Getting proxyBeanMethods() NosuchMethod Exception

I wrote a web service to connect to an URL which has custom params.
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import javax.servlet.http.HttpServletRequest;
import org.apache.http.client.utils.URIBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
#RestController
public class ServiceNowController {
private static final Logger logger = LoggerFactory.getLogger(ServiceNowController.class);
#CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
#RequestMapping(method = RequestMethod.GET, value = "/incident", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> retriveAllIncidents(HttpServletRequest request) throws UnsupportedEncodingException {
logger.info("ServiceNowController -> retrieveAllIncidents(): Invoked");
RestTemplate restTemplate = new RestTemplate();
ArrayList<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Collections.singletonList(MediaType.ALL));
messageConverters.add(converter);
restTemplate.setMessageConverters(messageConverters);
String mainUrl = "<url>";
final String sysparm_query = "param1";
final String sysparm_display_value = "param2";
final String decoded_sysparam_query = URLDecoder.decode(sysparm_query, StandardCharsets.UTF_8.toString());
System.out.println(decoded_sysparam_query);
try {
URIBuilder builder = new URIBuilder(mainUrl);
builder.addParameter(sysparm_query, decoded_sysparam_query);
builder.addParameter(sysparm_display_value, sysparm_display_value);
String finalUrl = builder.toString();
System.out.println(finalUrl);
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "<authorization token>");
headers.setAccept(Arrays.asList(MediaType.ALL));
HttpEntity<String> entity = new HttpEntity<String>(headers);
String urlString = "< url with params >";
String encodedUrl = URLEncoder.encode(urlString, StandardCharsets.UTF_8.toString());
String decodedUrl = URLDecoder.decode(encodedUrl.toString(), StandardCharsets.UTF_8.toString());
ResponseEntity<Object> results = restTemplate.exchange(decodedUrl, HttpMethod.GET, null, Object.class);
return results;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
}
Main class
package com.dell.servicenowapis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
#SpringBootApplication
public class ServicenowapisApplication {
public static void main(String[] args) {
SpringApplication.run(ServicenowapisApplication.class, args);
}
#Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
POM.XML
<?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.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.dell</groupId>
<artifactId>servicenowapis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>servicenowapis</name>
<description>Service Now API</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
When I try to run it, I get this stack trace.
org.springframework.core.annotation.AnnotationConfigurationException: Attribute 'proxyBeanMethods' in annotation [org.springframework.boot.SpringBootConfiguration] is declared as an #AliasFor nonexistent attribute 'proxyBeanMethods' in annotation [org.springframework.context.annotation.Configuration].; nested exception is java.lang.NoSuchMethodException: org.springframework.context.annotation.Configuration.proxyBeanMethods()
at org.springframework.core.annotation.AnnotationUtils$AliasDescriptor.<init>(AnnotationUtils.java:2089)
at org.springframework.core.annotation.AnnotationUtils$AliasDescriptor.from(AnnotationUtils.java:2056)
at org.springframework.core.annotation.AnnotationUtils.getAttributeAliasNames(AnnotationUtils.java:1726)
at org.springframework.core.annotation.AnnotationUtils.isSynthesizable(AnnotationUtils.java:1685)
at org.springframework.core.annotation.AnnotationUtils.synthesizeAnnotation(AnnotationUtils.java:1468)
at org.springframework.core.annotation.AnnotationUtils.synthesizeAnnotationArray(AnnotationUtils.java:1572)
at org.springframework.core.annotation.AnnotationUtils.getAnnotations(AnnotationUtils.java:231)
at org.springframework.core.type.classreading.AnnotationAttributesReadingVisitor.visitEnd(AnnotationAttributesReadingVisitor.java:76)
at org.springframework.asm.ClassReader.readAnnotationValues(ClassReader.java:2020)
at org.springframework.asm.ClassReader.accept(ClassReader.java:676)
at org.springframework.asm.ClassReader.accept(ClassReader.java:527)
at org.springframework.ide.eclipse.core.java.classreading.JdtConnectedMetadataReader.<init>(JdtConnectedMetadataReader.java:45)
at org.springframework.ide.eclipse.core.java.classreading.JdtMetadataReaderFactory.getMetadataReader(JdtMetadataReaderFactory.java:53)
at org.springframework.ide.eclipse.core.java.classreading.CachingJdtMetadataReaderFactory.getMetadataReader(CachingJdtMetadataReaderFactory.java:38)
at org.springframework.ide.eclipse.beans.core.internal.model.BeansJavaConfig.registerBean(BeansJavaConfig.java:368)
at org.springframework.ide.eclipse.beans.core.internal.model.BeansJavaConfig$2.call(BeansJavaConfig.java:229)
at org.springframework.ide.eclipse.beans.core.internal.model.BeansJavaConfig$2.call(BeansJavaConfig.java:1)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NoSuchMethodException: org.springframework.context.annotation.Configuration.proxyBeanMethods()
at java.lang.Class.getDeclaredMethod(Unknown Source)
at org.springframework.core.annotation.AnnotationUtils$AliasDescriptor.<init>(AnnotationUtils.java:2082)
... 22 more
Where am I making mistakes? How to fix this?
Although the pom looks OK to me, there is a chance that its a clash of old and new spring versions.
Note that proxyBeanMethods is added in spring boot 2.2.
Please open up the generated artifact without actually run it with tools like WinRar and check the BOOT-INF/lib folder.
Make sure you don't have older spring/spring-boot versions there.
The problem seems to be here. You are instantiating a bean for RestTemplate in main class and in the web service again you are creating a new object for the same. Try removing the bean definition
Remove the below lines
#Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}

WebSocket with embedded Tomcat is 404

I made two classes:
Main class with embedded Tomcat(8.5.20)
ServerEndpoint of Websocket
I run the main class on IntelliJ IDEA
and run this JavaScript: new WebSocket('ws://localhost:8080/ws')
in the console of Google Chrome.
I expected the response code is 200, but actually it is 404.
How can I fix this?
Main class:
package webapp;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import javax.servlet.ServletException;
import java.io.File;
public class Main {
private static final String STATIC_DIR = "src/main/static/";
public static void main(String[] args) throws ServletException, LifecycleException {
Tomcat tomcat = new Tomcat();
tomcat.setPort(8080);
File staticDir = new File(STATIC_DIR);
tomcat.addWebapp("/", staticDir.getAbsolutePath());
tomcat.start();
tomcat.getServer().await();
}
}
ServerEndpoint:
package webapp.websocket;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/ws")
public class SampleWebSocket {
#OnOpen
public void onOpen(Session session) {
System.out.println("open");
}
#OnClose
public void onClose(Session session) {
System.out.println("close");
}
#OnMessage
public String onMessage(String text) {
System.out.println("message:" + text);
return "Server:" + text;
}
}
Thank you.
I found a solution.
This question is dupricated.
I read Got 404 error on tomcat 7.0.47 websocket and editted my pom.xml.
Following is the whole of 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.example</groupId>
<artifactId>websocket-sample</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>websocket-sample</name>
<properties>
<java.version>1.8</java.version>
<maven.compiler.target>${java.version}</maven.compiler.target>
<maven.compiler.source>${java.version}</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>8.5.20</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-websocket</artifactId>
<version>8.5.20</version>
</dependency>
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
</dependency>
</dependencies>
</project>
Just add the following dependency to pom.xml
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-websocket</artifactId>
<version>8.5.20</version>
</dependency>
What solved the issue for me was switching from the javax.websocket-api dependency to the Tomcat-specific tomcat-embed-websocket dependency instead and switching all my imports (ServerEndpoint, onMessage, etc.) to the Tomcat-specific jakarta.websocket.* packages instead of the javax.websocket.x packages.
Here is the endpoint code that worked for me -- notice that there are no javax.websocket imports and instead I have jakarta.websocket imports:
import java.io.IOException;
import jakarta.websocket.EncodeException;
import jakarta.websocket.OnMessage;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
#ServerEndpoint("/echo")
public class EchoEndpoint {
// Implementation.
#OnMessage
public void onMessage(
Session session,
String message)
throws
IOException,
EncodeException {
// Send the same message back.
session.getBasicRemote().sendText(message);
}
}
And my pom.xml file dependencies:
<!-- https://mvnrepository.com/artifact/org.apache.tomcat.embed/tomcat-embed-core -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>10.1.0-M8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat.embed/tomcat-embed-websocket -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-websocket</artifactId>
<version>10.1.0-M8</version>
</dependency>
As far as I can tell, the pom.xml should not contain the javax.websocket dependency at all, to ensure there are no collisions/clashes between that one and the Tomcat-specific tomcat-embed-websocket dependency.

How do i catch bad URL requests using REST easy

I have a few endpoints under "/rest/role/"whatever"
how do i catch bad requests for example "rest/role/dbbhwbhb/wdwdwed
if i use :
#GET
#Path("/{param}")
#Produces(MediaType.TEXT_PLAIN)
public Response badURLS() {
return Response.ok().entity("bad url").build();
}
this catches rest/roles/dfsdfsds but rest/roles/sdsasd/asdad is still not caught. How do I set up a method so if none of my endpoints are hit then return a default message ?
JBoss approach
https://docs.jboss.org/jbportal/v2.7.0.B1/referenceGuide/html/errorhandling.html
RESTeasy approach
https://docs.jboss.org/resteasy/docs/2.2.0.GA/userguide/html/ExceptionHandling.html
EDIT
As I sent to you before - second link does the trick.
Given the mapper and structure written in such way:
package atata;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
#Provider
public class _404Handler implements ExceptionMapper<NotFoundException> {
public Response toResponse(NotFoundException exception) {
return Response.status(500).entity(new ResponseEntity(333, "Got 404.")).type(MediaType.APPLICATION_JSON).build();
}
}
Config
package atata;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
public class EmployeeApplication extends Application {
private Set<Object> singletons = new HashSet<Object>();
public EmployeeApplication() {
singletons.add(new MessageRestService());
singletons.add(new _404Handler());
}
#Override
public Set<Object> getSingletons() {
return singletons;
}
}
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>io.atata</groupId>
<artifactId>atata</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>atata Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.resteasy/resteasy-jaxrs -->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>3.0.19.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-servlet-initializer</artifactId>
<version>3.0.4.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<version>3.0.14.Final</version>
</dependency>
</dependencies>
<build>
<finalName>atata</finalName>
</build>
Endpoint:
package atata;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path("/roles")
public class MessageRestService {
#GET
#Path("/1")
#Produces(MediaType.APPLICATION_JSON)
public Response badURLS() {
return Response.ok().entity("OK").build();
}
}
You will get

Categories

Resources