Glassfish & MongoDB connection error : NoClassDefFoundError - java

I am running a Glassfish server that is trying to connect to MongoDB. At first I created seperate projects for the server and MongoDB. So now I am trying to merge those projects but it appears anything I try to do it results in a faliure.
The current error I am getting is:
2018-07-05T19:54:36.249+0200|Severe: java.lang.NoClassDefFoundError: org/bson/conversions/Bson
I am well aware that the error happens in runtime and that the possible cause is my classpath.
Currently I copied all of my code from one project to another, added Maven dependencies and the following happens:
if I create a separate .java file for my MongoDB and run it in the same folder that the Glassfish server is, it works perfectly fine.
if I run the server and try to call methods from the other class (a little bit modified) the upper error appears
Simplified code example withouth error:
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
public class MyClass{
public static void main(String[]args){
String ip = "127.0.0.1";
int port = 27017;
MongoClient mongoClient = new MongoClient(ip,port);
/* Remaining code */
}
}
With error:
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
public class MyClass{
private MongoClient mongoClient;
public MyClass(String ip, int port){
mongoClient = new MongoClient(ip, port); // Error called here
}
/* Remaining code */
}
Called from the server.java file:
MyClass mc = new MyClass("127.0.0.1",27017);
I also tried to download all of the bson jar files separately and add them to the project but that had no effect...

The working solution for me was to delete the whole project and create it once more. Apparently there was a problem with Eclipse or I made a mistake before and forgot about it.

Related

How can I call test method from jar file to run mock script

I have a deployment of a spring-based corporate project, I did everything and now I just need to run the data seeding script, but I don’t understand how to do it at all
The instructions say:
Run test build io.groobit.utils.mock_data_init.ScenarioTest#scenario1
run mock-init.jar in folder (not used run test in "Itelij idea" To avoid such an error .. see image)
Run build mock-init.jar "java -jar mock-init.jar"
I have run tests many times in intelij idea by clicking the desired method in the test folder, but how to proceed here in the command to call it?
package io.groobit.utils.mock_data_init;
import io.groobit.api.client_api.dto.BusinessClientBasicInfo;
import io.groobit.api.client_api.dto.Payment;
import io.groobit.utils.mock_data_init.*;
import io.groobit.utils.mock_data_init.utils.AuthUtils;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import java.math.BigDecimal;
import java.time.Instant;
#Slf4j
#Disabled
#SpringBootTest
#DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class ScenarioTest {
#Test
public void scenario1() throws Exception {
//call this it
}
}
Path test: src/test/java/io/company/utils/mock_data_init/ScenarioTest.java
Any idea?

"Class path resource [config/game.properties] cannot be opened because it does not exist" IntelliJ - Spring project not looking in correct directory?

I'm making a Java Spring project in IntelliJ as an exercise and I don't understand a file configuration error I'm having.
Please look at my project directory layout as described in this screenshot:
The three most important files here are the Main & GameConfig classes, and the game.properties file. Or, to use their full package directory names, "console/src/main/java/academy.learnprogramming.console.Main", "core/src/main/java/academy.learnprogramming.config.GameConfig" and core/src.resources.config.game.properties
When I run project, the Main class tries to run the following code:
package academy.learnprogramming.console;
import academy.learnprogramming.MessageGenerator;
import academy.learnprogramming.NumberGenerator;
import academy.learnprogramming.config.GameConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
private static final Logger log = LoggerFactory.getLogger(com.sun.tools.javac.Main.class);
public static void main(String[] args) {
log.info("Guess the number");
//== create the context first ==
ConfigurableApplicationContext context
= new AnnotationConfigApplicationContext(GameConfig.class);
// rest of code, which we never get to because of an error with the above line
When I try to create ConfigurableApplicationContext, I am trying to call the GameConfig class from the Core package. But I get this runtime error instead:
Exception in thread "main"
org.springframework.beans.factory.BeanDefinitionStoreException: Failed
to parse configuration class
[academy.learnprogramming.config.GameConfig]; nested exception is
java.io.FileNotFoundException: class path resource
[config/game.properties] cannot be opened because it does not exist
I do not understand why it thinks GameConfig does not exist, or how to fix it. No solutions I have found seem to have the precise answer for this. I have gotten a configuration comparison from someone whose code is identical to mine, but neither of us understand why their version works and mine does not.
For comparison's sake, the GameConfig class has the following code:
package academy.learnprogramming.config;
import academy.learnprogramming.GuessCount;
import academy.learnprogramming.MaxNumber;
import academy.learnprogramming.MinNumber;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
#Configuration
#ComponentScan(basePackages = "academy.learnprogramming")
#PropertySource("classpath:config/game.properties")
public class GameConfig {
//rest of GameConfig code here...
While game.properties is as simple as this:
game.maxNumber = 100
game.guessCount = 10
game.minNumber = 0
I can't find a question similar to this, nor do other websites point out what's going on. Does anyone have any idea why this error might be happening? Any advice would be invaluable

Stringing together multiple page object files in Eclipse/Cucumber/Java

I am having trouble stringing together multiple Page Object Files and step definitions.
I have imported the following, which is super heavily edited due to it being work code:
package <the package my step definition file is in>
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import <the other project my team created>.browsercapabilities.Browser;
import <the other project my team created>.Browsers;
import <a package a different step definition file is
in>.addNewContact.AddNewContactStepDefs;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import <the other project my team created>.webcomponents.WebButton;
import <my page objects package>.authenticationpages.CommandLoginPage;
import <my page object package>ThirdPageObjectFile;
import <my page object package>.SecondPageObjectFile;
import <my page object package>.FirstPageObjectFile;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.When;
public class ThirdPageStepDefs extends BrowserBase {
private static final Logger LOG =
LoggerFactory.getLogger(ThirdPageStepDefs.class);
private WebDriver driver = mainBrowser().getDriver();
private Browser browser = Browsers.getBrowser();
private WebDriverWait wait = new WebDriverWait(driver,10);
LoginPage login = new LoginPage (browser);
SecondPageObjectFile contact = new SecondPageObjectFile (browser);
FirstPageObjectFile searchContact = new FirstPageObjectFile (browser);
ThirdPageObjectFile deal = new ThirdPageObjectFile (browser);
#Then("^I click the contacts icon$")
public void i_click_the_contacts_icon() throws Throwable {
contact.get_contact_link().clickLink();
}
I was getting an initialization error when I ran the runner code saying that the runner could not instantiate an instance of my ThirdStepDefFile, i.e. "Failed to Instantiate Class "
My runner is working fine:
package <Utility package>.utilities;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import cucumber.api.testng.AbstractTestNGCucumberTests;
#RunWith(Cucumber.class)
#CucumberOptions(
features="src\\test\\resources\\<my feature folder>",
plugin={"pretty", "html:target/cucumber-html-report",
"json:target/cucumber.json"},
glue= "<My step def folder>",
tags = "#<my tags>"
)
public class ComUITestRunner extends AbstractTestNGCucumberTests {
}
I have many more lines in scenarios that I've commented out and since I was getting the initialization error, I edited to troubleshoot as following:
-Comment all methods out (green)
-Leave all methods in (red)
-Leave one method in (red)
When I have even one method that isn't commented out, then I get an error.
My project is a series of screens that a user has to get to in order to log in. The login screen, first screen, second screen, and third screen all have their own page objects. Eventually I want to abstract those screens out to a main project that all sub projects share as they'll be pre-conditions to everything else. Stringing these screens together seems to fail and I'm considering refactoring the whole thing.
Am also new to Java/Eclipse, so it's possible that I am not seeing the stack trace correctly. For instance, the bottom of my junit screen says "62 more" lines detailing the failure that I'm not able to see. I tried debugging to no avail and I clicked on the outline on the left hand side of the junit output and when I hovered over it, it says Test Class Not Found

Errors in good syntax after using new machine [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have imported project to my new machine (to eclipse) and it threw 88 errors even that on previous machine it was working good. here are the types of errors:
MINUTES cannot be resolved or is not a field
Syntax error
Method not applicable to arguments
isEmpty() undefined
And when I check it all of syntax is good etc.
Anyone had similar problem?
Here's code which throws an exception (MINUTES cannot be resolved or is not a field )
try {
TimeUnit.MINUTES.sleep(Config.DOCS_CHECK_INTERVAL);
} catch (InterruptedException e) {
log.error("Exception", e);
}
Imports:
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.security.cert.X509Certificate;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.ikubasienki.core.Config;
All of your errors suggest that you are using an outdated Java Version. For example, in Java 5, there was no TimeUnit.MINUTES: https://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/TimeUnit.html. It has been added in Java 6.
Assumed that you are calling isEmpty() on a String Object, the same is true: String.isEmpty() has been added in Java 6: https://docs.oracle.com/javase/6/docs/api/java/lang/String.html#isEmpty(), hence you would get an isEmpty() undefined error when building the project with Java 5.
Please check the settings of the "JRE System Library" you are using to build the project in Eclipse:
Verify that the path shown for the jar files matches the java runtime you want to use.
If that still does not help, create a new Project in Eclipse with a simple class like
package com.example;
public class Simple {
public static void main(String[] args) {
System.err.println(System.getProperty("java.version"));
System.err.println("".isEmpty());
}
}
and run it. The output should be something like
1.7.0_80
true
Another common source of errors is the Compiler Compliance Level setting of your project:
However, this would not explain the "undefined symbol" errors since it affects the language level only (e.g. whether enum or generics are allowed). It might explain your syntax error, though.
Make sure your custom jre in eclipse points to jre folder (if you're using jde make sure twice it's not ponting to jde but to jre inside jde!!)!

Mongodb database is not created

I am creating mongodb database and trying to insert records in it but problem is that database is not created
My database name is "myMongoDB" and collection name is chanel when i run it,it gives
error and with BUILD SUCCESSFUL
package databaseconnection;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import java.net.UnknownHostException;
public class InsertDriver {
public static void main(String args[])throws UnknownHostException
{
DB db=(new MongoClient("localhost",8080)).getDB("myMongoDB");
DBCollection dbcollection=db.getCollection("chanel");
BasicDBObject basicDBObject=new BasicDBObject();
basicDBObject.put("name", "dhiraj");
basicDBObject.put("subscription", 4100);
dbcollection.insert(basicDBObject);
}
}
Exception in thread "main" java.lang.NoSuchMethodError: com.mongodb.ReadPreference.primary()Lcom/mongodb/ReadPreference;
at com.mongodb.MongoClientOptions$Builder.<init>(MongoClientOptions.java:52)
at com.mongodb.MongoClient.<init>(MongoClient.java:128)
at com.mongodb.MongoClient.<init>(MongoClient.java:117)
at databaseconnection.InsertDriver.main(InsertDriver.java:21)
It looks like you mix several different versions of java mongodb client library.
If you take a look at this version of ReadPreference for instance http://grepcode.com/file/repo1.maven.org/maven2/org.mongodb/mongo-java-driver/2.7.3/com/mongodb/ReadPreference.java you'll see that there is no "primary" method there. But in different version it's there: http://grepcode.com/file/repo1.maven.org/maven2/org.mongodb/mongo-java-driver/2.9.1/com/mongodb/ReadPreference.java#ReadPreference.primary%28%29
Can you please list all jars from your classpath for more detailed help. It could be that classes from old mongodb client were added into some other jar.
One thing I want to clear, Databases are created in MongoDB when you insert some data in any collection of that database.
First of all, check MongoDB is running on your machine (By default it will run on port 27017)?
Try to insert some sample data from mongo shell.
sample commands:
use testDB
db.testCollection.insert({"name":"dev"});
It will inset this data in testCollection of testDB database. You can find it using :
db.testCollection.find()
If all this working fine. Then proceed with java driver.
You code looks good besides that 8080 port (I am assuming you manually changed the port from 27017 to 8080) and make sure MongoDB is running.
Actually i dont know what was wrong with my previous code but i uninstalled the
mongodb completly and then reinstalled it and tried following code and it worked fine for me .
package mongod;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.net.UnknownHostException;
import java.util.List;
public class Mongod {
//private static Object mongo;
Mongod mongo;
public static void main(String[] args) throws UnknownHostException {
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB db = mongoClient.getDB("testDB1");
DBCollection dbcollection=db.getCollection("testCollection");
BasicDBObject basicDBObject=new BasicDBObject();
basicDBObject.put("name", "dhiraj");
basicDBObject.put("subscription", 4100);
dbcollection.insert(basicDBObject);
//boolean auth = db.authenticate("admin", "admin123".toCharArray());
//System.out.println(auth);
List<String> dbs = mongoClient.getDatabaseNames();
for (String dbss : dbs) {
System.out.println(dbss);
}
}
}

Categories