I created a Maven project and when I run all the unit tests for the project through eclipse, all of them pass as expected. But when I do a mvn install through a terminal, I see the following error for the test testPredictThrowsException():
testPredictThrowsException(com.ner.core.NamedEntityRecognizerTest) Time elapsed: 0.001 sec <<< ERROR!
java.lang.NullPointerException
at com.ner.core.NamedEntityRecognizer.train(NamedEntityRecognizer.java:70)
at com.ner.core.NamedEntityRecognizerTest.setUp(NamedEntityRecognizerTest.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
...which means that the object ner that I am instantiating in the #Before setUp() method is not being run resulting it in being set to null. Here are the tests and POM.xml. Thoughts?
public class NamedEntityRecognizerTest {
NamedEntityRecognizer ner;
#Before
public void setUp() throws NamedEntityRecognizerException {
ner = new NamedEntityRecognizer();
InputStream trainingStream = NamedEntityRecognizerTest.class.getClassLoader().getResourceAsStream("trainingData1.train");
ner.train(trainingStream);
}
#Test(expected=NamedEntityRecognizerException.class)
public void testPredictThrowsException() throws NamedEntityRecognizerException {
System.out.println("NERRRR: " + ner);
ner.predict(null);
}
}
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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ner</groupId>
<artifactId>AmpelloNER</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>AmpelloNER</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<!-- more dependencies go here... -->
</dependency>
</dependencies>
</project>
UPDATE:
Just figured out that the NullPointerException was being thrown when I try getting the absolute path of a file in test/resources/ directory (See code below). It is able to find that file when I run the test through eclipse, but, when I try running it through the terminal by typing mvn install, it throws a NullPointerException. How can I resolve this issue?
#Before
public void setUp() throws NamedEntityRecognizerException {
ner = new NamedEntityRecognizer();
String trainingFile = NamedEntityRecognizerTest.class.getClassLoader().getResourceAsStream("trainingData1.train");
ner.train(trainingFile); // <<<---- This throws the NPE
}
Related
I try to use Okhttp and Scarlet library but when I run project this exception throws.
how can I fix it? I search about it and I found out that the version of https is not the same in different library I added to my maven.in my maven dependency i see okhttp-4.9.1.jar and I do NOT know how i can change the version of that.
please help me ...
Exception in thread "main" java.lang.NoSuchFieldError: Companion
at okhttp3.internal.Util.<clinit>(Util.kt:71)
at okhttp3.OkHttpClient.<clinit>(OkHttpClient.kt:1073)
at crypto.Main.main(Main.java:16)
my pom.xml file :
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cripto</groupId>
<artifactId>crypto</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.tinder.scarlet</groupId>
<artifactId>websocket-okhttp</artifactId>
<version>0.1.12</version>
</dependency>
<dependency>
<groupId>com.tinder.scarlet</groupId>
<artifactId>scarlet</artifactId>
<version>0.1.12</version>
</dependency>
<dependency>
<groupId>com.tinder.scarlet</groupId>
<artifactId>message-adapter-gson</artifactId>
<version>0.1.12</version>
</dependency>
</dependencies>
</project>
public static String Url = "wss://stream.binance.com:9443" ;
public static void main(String[] args) {
// TODO Auto-generated method stub
OkHttpClient client = new OkHttpClient() ;
System.out.println(client) ;
Scarlet scarlet = new Scarlet.Builder()
.webSocketFactory(OkHttpClientUtils.newWebSocketFactory(client,Url))
.addMessageAdapterFactory(new GsonMessageAdapter.Factory())
//.addStreamAdapterFactory(new RxJava2StreamAdapterFactory())
.build() ;
}
To view where the okhttp dependency is coming from please run the below command this will display the dependency in a tree format
mvn dependency:tree
Once you figure out where the dependency is populated from, you can exclude(How to exclude dependency in a Maven plugin?) okhttp from there, and add your required version.
Im trying to configure Websockets on my tomcat server but I'm not able to set the endpoint. But I keep getting error
error: cannot find symbol #ServerEndpoint("/websocketendpoint")
I installed the javax.websocket api but im still missing javax.websocket.server package. I've tried installing every java websocket package I could find and still doesnt work.
Is it supposed to be a part of my tomcat server, java 11 or openJDK, or do I just have to get from somewhere online? I've not been able to find this package till now. All other anotations work when I compile with websocket-api.jar
import javax.naming.*;
import java.io.*;
import java.util.*;
import org.json.*;
import javax.naming.*;
import javax.websocket.*;
#ServerEndpoint("/websocketendpoint")
public class OffisEndpoint{
private Session session;
#OnOpen
public void onOpen(Session session){
this.session = session;
}
#OnMessage
public void onMessage(String message){
try{
if(this.session != null && this.session.isOpen()){
this.session.getBasicRemote().sendText("From Server"+ message);
}
}catch(Exception e){
}
}
#OnClose
public void onClose(){
System.out.println("Close Connection ...");
}
#OnError
public void onError(Throwable e){
e.printStackTrace();
}
}
You're not going to be able to live without a build tool very long as you move forward. For this code I used maven to get going. Maven assumes a particular directory structure so your environment would look like:
pom.xml
src/
main/
java/
com/
example/
websocket/
OffisEndpoint.java
The first line in OffisEndpoint.java will now be package com.example.websocket; to indicate that the file now lives in a Java package.
The contents of pom.xml are:
<?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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>websocket</artifactId>
<version>1.0.0</version>
<packaging>war</packaging>
<properties>
<failOnMissingWebXml>false</failOnMissingWebXml>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
You'll need to install Maven to be able to use it. See the Install instructions for more detail.
Once you get Maven installed, change to the directory where your pom.xml file lives and run mvn clean package. This will download files that are needed one time. The next time you build it will not take very long.
The build creates target/websocket-1.0.0.war. This can be deployed to a running Tomcat by copying it to the webapps directory.
You will access this websocket endpoint through http://localhost:8080/websocket/websocketendpoint. The extra path element is because your code is deploy the the websocket web application.
This question already has answers here:
Unable to derive module descriptor: Provider {class X} not in module
(2 answers)
Closed 1 year ago.
Error occurred during initialization of boot layer
java.lang.module.FindException: Unable to derive module descriptor for C:\Users\admin\eclipse-workspace\Testing\lib\selenium-server-standalone.jar
Caused by: java.lang.module.InvalidModuleDescriptorException: Provider class org.eclipse.jetty.http.Http1FieldPreEncoder not in module
package Testing;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
public class Testing {
public static void main(String[] args) throws InterruptedException
{
Selenium selenium= new DefaultSelenium("localhost",4444,"firefox","http://www.calculator.net");
selenium.start();
selenium.open("/");
selenium.windowMaximize();
selenium.click("xpath=.//*[#id=''hl3']/li[3]/a");
Thread.sleep(4000);
selenium.focus("id=cpar1");
selenium.type("css=input[id=\"cpar1\"]", "10");
selenium.focus("id=cpar2");
selenium.type("css=input[id=\"cpar2\"]", "50");
(selenium).click("xpath=.//*[#id='content']/table[1]/tbody/tr[2]/td/input[2]");
// verify if the result is 5
Thread.sleep(4000);
String result = selenium.getText("xpath=.//*[#id='content']/p[2]/font/b");
//String result = selenium.getValue("xpath=.//*[#id='cpar3']");
System.out.println("Result:"+result);
if (result.equals("5")/*== "5"*/){
System.out.println("Pass");
}
else{
System.out.println("Fail");
}
}
}
I would recommend reconsidering using Selenium Remote Control as it is quite outdated approach which is no longer supported, current stable version of Selenium Java client is 3.141.59 and it provides WebDriver API which is a W3C Standard as of now.
Once you implement option 1 get rid of those Thread.sleep() as it's a some form of a performance anti-pattern, go for Explicit Wait instead, check out How to use Selenium to test web applications using AJAX technology for comprehensive explanation and code examples.
It's better to use a dependency management solution like Apache Maven which will automatically detect and download your project transitive dependencies. A relevant pom.xml file would be something like:
<?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>com.example</groupId>
<artifactId>selenium</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
</dependencies>
</project>
I added to my web project geoip2 using maven but in the code when im trying to use it, the Import is not working. I can see the jar in maven dependencies but i can't use it. I need some help.
I know it's not a complete answer to your problem, but it's too long for a comment.
I've built a sample project using geoip2. POM is as follows:
<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.test</groupId>
<artifactId>geoip</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>geoip</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>2.0.0</version>
</dependency>
</dependencies>
</project>
And the Java code:
package com.test;
import com.maxmind.geoip2.WebServiceClient;
import com.maxmind.geoip2.model.CountryResponse;
public class App {
public static void main(String[] args) throws Exception {
int userId = 0;
String licenseKey = "key";
WebServiceClient client = new WebServiceClient.Builder(userId, licenseKey).build();
CountryResponse response = client.country();
System.out.println(response.getCountry().getName());
}
}
I can't reproduce your import problem. It works just fine. You can download this test here: geoip2-test.zip
Check if you can build your project from command line with: mvn clean install
If so, then maybe it's a misconfiguration problem in your project or IDE.
It's Eclipse? Try Maven -> Update Project. Sometimes this works for me when I add new dependencies that are not immediately detected.
if you use intellij, then first close project and then import project and use auto import for the SBT project.then com.maxmind.geoip2 is resolved.
I have found a strange interaction between cobertura-maven-plugin 2.6 and jmockit 1.8. A particular pattern in our production code has a class with a lot of static methods that effectively wraps a different class that acts like a singleton. Writing unit tests for these classes went fine until I tried to run coverage reports with cobertura, when this error cropped up:
java.lang.ExceptionInInitializerError
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: java.lang.NullPointerException
at com.example.foo.MySingleton.<clinit>(MySingleton.java:7)
... 13 more
This then leads to a NoClassDefFoundError and being unable to initialize the singleton class. Here's a full SSCCE (the shortest I can get it down to) that replicates the error; line 7 of MySingleton is Logger.getLogger().
Here's the "singleton"...
package com.example.foo;
import org.apache.log4j.Logger;
public class MySingleton {
private static final Logger LOG = Logger.getLogger(MySingleton.class);
private boolean inited = false;
private Double d;
MySingleton() {
}
public boolean isInited() {
return inited;
}
public void start() {
inited = true;
}
public double getD() {
return d;
}
}
And the static class...
package com.example.foo;
import org.apache.log4j.Logger;
public class MyStatic {
private static final Logger LOGGER = Logger.getLogger(MyStatic.class);
private static MySingleton u = new MySingleton();
public static double getD() {
if (u.isInited()) {
return u.getD();
}
return 0.0;
}
}
And the test that breaks everything...
package com.example.foo;
import mockit.Expectations;
import mockit.Mocked;
import mockit.Tested;
import org.junit.Test;
public class MyStaticTest {
#Tested MyStatic myStatic;
#Mocked MySingleton single;
#Test
public void testThatBombs() {
new Expectations() {{
single.isInited(); result = true;
single.getD(); /*result = 1.2;*/
}};
// Deencapsulation.invoke(MyStatic.class, "getD");
MyStatic.getD();
}
}
And the maven 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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example.foo</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Test</name>
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<version>1.8</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.6</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
To summarize the summary: When running an ordinary unit test (mvn clean test), the above tests just fine; when run with cobertura (mvn clean cobertura:cobertura) it throws the nasty set of exceptions shown at the top. Obviously a bug somewhere, but whose?
The cause for this problem isn't so much a bug, but a lack of robustness in JMockit when mocking a class that contains a static initializer. The next version of JMockit (1.9) will be improved on this point (I already have a working solution).
Also, the problem would not have occurred if Cobertura marked its generated methods (four of them with names starting with "__cobertura_", added to every instrumented class) as "synthetic", so that JMockit would have ignored them when mocking a Cobertura-instrumented class. Anyway, fortunately this won't be necessary.
For now, there are two easy work-arounds which avoid the problem:
Make sure any class to be mocked was already initialized by the JVM by the time the test starts. This can be done by instantiating it or invoking a static method on it.
Declare the mock field or mock parameter as #Mocked(stubOutClassInitialization = true).
Both work-arounds prevent the NPE that would otherwise get thrown from inside the static class initializer, which is modified by Cobertura (to see these bytecode modifications, you can use the javap tool of the JDK, on classes under the target/generated-classes directory).