How to run jsoup code from maven in Eclipse? - java

I created a new maven project in Eclipse and created a file Main.java under src/main/java/parser. Here the package is parser in which my Main.java file is located. Here are the contents of Main.java, which is an example from Jsoup website.
package parser;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Main {
public static void main(String[] args) throws Exception {
Document doc = Jsoup.connect("http://en.wikipedia.org/").get();
System.out.println(doc.title());
Elements newsHeadlines = doc.select("#mp-itn b a");
for (Element headline : newsHeadlines) {
System.out.println(headline.attr("title") + "\n\t" + headline.absUrl("href"));
}
}
}
Here is the 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>mdlparser</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<!-- jsoup HTML parser library # https://jsoup.org/ -->
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.3</version>
</dependency>
</dependencies>
</project>
Now, how can I run this project? I right clicked pom.xml file and hit Maven Build which opened run configuration window. What am I supposed to type here? I tried typing package and eclipse:eclipse. In both cases, the console's output says that the build was successful, but the output from my program(System.out.println) is not being shown in the console. Also I tried running it as simple java application but in that case I get NoClassDefFoundError.
Note: I know that you usually use a logger instead of using sysout. But I am really confused as to how to run this simple hello world like program.

Related

How do I include src/test/java files to run TestNG tests?

I'm just learning Java and could use your help. I'm using Eclipse, and created a Maven project using the org.openjfx archetype. Everything seems to work fine except when I try to write tests in src/test/java, which causes an error.
An error occurred while instantiating class
starcraft.warcraft.test.TestClass: Unable to make public
starcraft.warcraft.test.TestClass() accessible: module
starcraft.warcraft does not "exports starcraft.warcraft.test" to
module org.testng
This is how I created the project with default settings in Eclipse:
Project Setup with Maven Archetype Selection
Now, when Eclipse creates the project, it doesn't have a src/test/java folder, so I create that manually. Then I create a class called "TestClass" inside a package "starcraft.warcraft.test" inside src/test/java, and I add a simple method to test inside the App class called "adder". You can see the project structure
Project Structure
package starcraft.warcraft;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class App extends Application {
#Override
public void start(Stage stage) {
var javaVersion = SystemInfo.javaVersion();
var javafxVersion = SystemInfo.javafxVersion();
var label = new Label("Hello, JavaFX " + javafxVersion + ", running on Java " + javaVersion + ".");
var scene = new Scene(new StackPane(label), 640, 480);
stage.setScene(scene);
stage.show();
}
// WILL TEST THIS METHOD
public static int adder(int digit1, int digit2) {
return digit1 + digit2;
}
public static void main(String[] args) {
launch();
}
}
Now I want to use TestNG for the tests, and so I include it in my POM which is
<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>starcraft</groupId>
<artifactId>warcraft</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>13</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.5</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<release>11</release>
</configuration>
</plugin>
<plugin>
<groupId>org.openjfx</groupId>
<artifactId>javafx-maven-plugin</artifactId>
<version>0.0.6</version>
<executions>
<execution>
<!-- Default configuration for running -->
<!-- Usage: mvn clean javafx:run -->
<id>default-cli</id>
<configuration>
<mainClass>starcraft.warcraft.App</mainClass>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
This is the default POM created by the Maven archetype except for the TestNG dependency I added. When I try to use TestNG, Eclipse makes me add it to the module path like so:
Maven saying I need to add the TestNG library
And here is my module-info:
module starcraft.warcraft {
requires javafx.controls;
requires org.testng;
exports starcraft.warcraft;
}
OK, all good so far, but now when I try to run my test inside TestClass:
package starcraft.warcraft.test;
import org.testng.annotations.Test;
import starcraft.warcraft.App;
public class TestClass {
#Test
public void testAdder() {
int sum = App.adder(1, 2);
System.out.println(sum);
}
}
I get the error, which again is
An error occurred while instantiating class
starcraft.warcraft.test.TestClass: Unable to make public
starcraft.warcraft.test.TestClass() accessible: module
starcraft.warcraft does not "exports starcraft.warcraft.test" to
module org.testng
I can't figure out how to do the export. When I try making the entry in module-info, it doesn't give me the option of adding the package in src/test/java, the only packages it allows me to choose from are in src/main/java.
I don't understand modules well. How can I get the program to let me run tests from src/test/java?
Thanks everyone who looked at this. I solved it by following these steps:
Delete module-info.java. This turns it into a nonmodular project which is fine for me. I hesitated to do this because the Maven JavaFX archetype included it, but as it says here somewhere
https://openjfx.io/openjfx-docs/#IDE-Eclipse
you can just delete it after its created.
The problem then if you try to run the project is it will give you a warning that JavaFX isn't included as a module. It will still run, but its best to get rid of this incase of problems down the road. So you need to download the JavaFX libraries, place them in your hard drive, and then include them in your project via VM arguments in Eclipse:
right click project -> Run configuration -> Arguments tab -> add in the VM arguments area something like:
--module-path [fully qualified path to lib folder containing downloaded JavaFX] --add-modules javafx.controls
path would be like "C:\javafx\lib" or wherever you placed the downloaded JavaFX.
Then it should run, and project will still build using Maven, but I'm not sure if its using the JavaFX which is still in the Maven POM or the one I specified on the C drive. But it works. Any help on whats happening there would be appreciated. Thanks

How to import java project as module in java web project using intelijj?

I wanted to use the class from basic java project inside java servlet class which is defined in another project.
I tried importing project as module through the module dependency InteliJ menu.
At compile time ,it is not giving any error ,but after running the server(Glassfish) and calling the servlet it is giving below error.
java.lang.NoClassDefFoundError: com/practise/LogFileCreator at UserLoginValidator.dbConnectionMaker(UserLoginValidator.java:31)>
Please find below code which causing error.
below class is from web project
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.*;
import com.practise.LogFileCreator;
public class UserLoginValidator extends HttpServlet
{
public String LogFilePath="D:\\Logs";
public PrintWriter out;
String errormsg="";
//********************
LogFileCreator l ;
#Override
public void init() throws ServletException {
try {
this.l = new LogFileCreator(LogFilePath); // here i am trying to create object of my class which causing the mentioned error.
l.WriteLog("Hello");
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
}
}
below class is from normal java project
package com.practise;
import java.io.*;
public class LogFileCreator
{
private String filepath;
private StringBuffer sb = new StringBuffer("Log");
private File file;
private FileWriter fileWriter;
private BufferedWriter bufferedWriter;
public PrintWriter p;
public LogFileCreator(String filepath) throws IOException
{
this.filepath=filepath;
String filename=sb.toString().concat(java.time.LocalDate.now().toString());
this.file = new File(this.filepath,filename);
this.fileWriter= new FileWriter(file,true);
if(!file.exists())
{
file.createNewFile();
}
p= new PrintWriter(fileWriter);
}
public void WriteLog(String logMessage){
p.println(java.time.LocalDateTime.now() + " : " + logMessage);
p.flush();
}
}
Here is the image for module dependency I used .
Image
Earlier I was using LogFileCreator.java class from same web project and it was working fine
Here what i am trying to acheive is ,without writing the LogFileCreator class again in web project ,wants to reuse the class written already inside normal java project to print the logs in desired text file .
Any solution/suggestions would be appreciated.
Thank you!
[Edit 1]
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>org.example</groupId>
<artifactId>webapp</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependencies>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>5.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>9.4.0.jre11</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.example</groupId>
<artifactId>Logging</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
<!-- String Driver= "com.microsoft.sqlserver.jdbc.SQLServerDriver";-->
<!-- String dbusername="sa";-->
<!-- String dbpassword="Admin#123";-->
<!-- String connectionString="jdbc:sqlserver://localhost:1433;databasename=Users;";-->
<!-- -->
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
</project>
Here What I did which resolved the above problem.
First I converted my first basic java project to maven project .
secondly I added maven dependency for the 2nd project (web project) and also added the jar file (of first project classes ) inside the web INF/lib directory of web project using below option from InteliJ .
Image
The server's classloader does not have a copy of LogFileCreator.class so the class is not on it's classpath.
It is probably how the deployment file (assuming war) was packaged. How are you building the file? Maven, Gradle, neither, etc.?
Edit
I wanted to give a bit more clarity for others who might stumble upon a similar issue. During compile time, the project/module in question was imported; however, maven does not know to package that library in the generated war. When it was deployed to Glassfish, the war did not contain the LogFileCreator class because it was not packaged in the war. The authors solution worked because maven is packaging the module into the war and Glassfish can now find the class.

An internal error occurred during: "Updating Deployment Scanners for Server: WildFly 23"

I'm trying to connect to my http://localhost: 8080/spring-boot-test/ui, but unfortunately I fail because I have errors on Eclips. WildFly 23 theoretically worked, because I normally get their localhost
An internal error occurred during: "Updating Deployment Scanners for Server: WildFly 23".
Could not initialize class org.wildfly.security.auth.client.DefaultAuthenticationContextProvider
An internal error occurred during: "Checking Deployment Scanners for server".
Could not initialize class org.wildfly.security.auth.client.DefaultAuthenticationContextProvider
When I try to redirect the directory in standalone.xml to a target with META-INF and WEB-INF, I come across two ERRORs
ERROR [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) WFLYDS0011: The deployment scanner found a directory named META-INF that was not inside a directory whose name ends with .ear, .jar, .rar, .sar or .war. This is likely the result of unzipping an archive directly inside the C:\Users\adame\eclipse-workspace\spring-boot-test\target directory, which is a user error. The META-INF directory will not be scanned for deployments, but it is possible that the scanner may find other files from the unzipped archive and attempt to deploy them, leading to errors.
ERROR [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) WFLYDS0011: The deployment scanner found a directory named WEB-INF that was not inside a directory whose name ends with .ear, .jar, .rar, .sar or .war. This is likely the result of unzipping an archive directly inside the C:\Users\adame\eclipse-workspace\spring-boot-test\target\ directory, which is a user error. The WEB-INF directory will not be scanned for deployments, but it is possible that the scanner may find other files from the unzipped archive and attempt to deploy them, leading to errors.
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>com.adamkaim.spring</groupId>
<artifactId>spring-boot-test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-spring-boot-starter</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
<properties>
<java.version>16</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<packaging>war</packaging>
</project>
App.java
package com.adamkaim.spring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
Address.java
package com.adamkaim.spring;
import org.springframework.stereotype.Component;
#Component
public class Address {
private String address="Wall Street 34";
public String getAddress() {
return this.address;
}
}
Student.java
package com.adamkaim.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component
public class Student {
#Autowired
private Address address;
public String showInfo(){
return this.address.getAddress();
}
}
MainView.java
package com.adamkaim.spring;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.server.VaadinRequest;
import com.vaadin.spring.annotation.SpringUI;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
#SuppressWarnings("serial")
#SpringUI(path="/ui")
#Title("Titlett")
#Theme("valo")
public class MainView extends UI{
#Override
protected void init(VaadinRequest request) {
final VerticalLayout verticalLayout = new VerticalLayout();
verticalLayout.addComponent(new Label("Welcome"));
Button button = new Button("Click me");
verticalLayout.addComponent(button);
button.addClickListener(new Button.ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
verticalLayout.addComponent(new Label("Button is clicked.."));
}
});
setContent(verticalLayout);
}
}
I was having the same error when trying to start a Wildfly 19.1.0 container from Eclipse (2021-09). The container seemed to start successful, but this message was driving me crazy.
After a while I came across this message on the Wildfly Google Groups, and this solved my problems!
Adding --add-opens=java.base/java.security=ALL-UNNAMED to eclipse.ini
fixed the issue on my side
Thanks to the original author, Rahim Alizada, in https://groups.google.com/g/wildfly/c/_OuPrpsF2pY/m/xLt6u-IfBgAJ.
The option --add-opens opens up the informed modules (all types and members) at runtime, allowing deep reflection from the target modules (in this case, everyone else - ALL-UNNAMED).
More about this option in the JEP 261.
I tried running Eclipse with only Java 8 in my system, if I remember it well I got it working, but some modules on these newer Eclipse versions require Java 11 to load properly.
I came across this error during the deployment of wildfly 23 server in eclipse
An internal error occurred during: "Updating Deployment Scanners for Server: WildFly 23". Could not initialize class org.wildfly.security.auth.client.DefaultAuthenticationContextProvider
This solved my issue too
Adding --add-opens=java.base/java.security=ALL-UNNAMED to eclipse.ini

Connect to AEM 6.0 JCR: Precondition Failed

I am having some issues connecting to the JCR repository within AEM 6.0. When I get to the point of creating a session on the repostory I get a javax.jcr.lock.LockException: Precondition Failed.
I have been using this tutorial to get started.
Here is my very simple code sample:
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.jcr.Repository;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import org.apache.jackrabbit.commons.JcrUtils;
import com.opencsv.CSVReader;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Repository repository;
FileReader fileReader;
CSVReader csvReader;
try {
System.out.println("connecting to repository");
repository = JcrUtils.getRepository("http://localhost:4502/crx/server");
Session session = repository.login( new SimpleCredentials("admin", "admin".toCharArray())); // throws javax.jcr.lock.LockException: Precondition Failed
}
catch(Exception e) {
System.out.println(e);
}
}
}
Any guidance would be greatly appreciated.
Inside a JCR repository, content is organized into one or more workspaces, each of which holds of a hierarchical structure of nodes and properties. So to create a jcr session & access node and properties you have to pass workspace with credentials, Default AEM workspace is crx.default
Instead of :
Session session = repository.login( new SimpleCredentials("admin", "admin".toCharArray()));
Use :
Session session = repository.login( new SimpleCredentials("admin", "admin".toCharArray()),"crx.default");
Please check the below link
javax.jcr.lock.LockException:Precondition Failed
The Obvious first: Is the AEM server running?
Secondly: Maybe your build environment is not set up correctly
I was able to set up a working project using your code and this maven file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.stackoverflow.test</groupId>
<artifactId>access_crx_from_outside</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>javax.jcr</groupId>
<artifactId>jcr</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.apache.jackrabbit</groupId>
<artifactId>jackrabbit-jcr-commons</artifactId>
<version>2.7.4</version>
</dependency>
<dependency>
<groupId>org.apache.jackrabbit</groupId>
<artifactId>jackrabbit-jcr2dav</artifactId>
<version>2.6.0</version>
</dependency>
</dependencies>

Selenium Maven Setup - One Empty Jar

I'm trying to set up a Java Selenium test using the recommended Maven instructions found here:
http://docs.seleniumhq.org/docs/03_webdriver.jsp
and here:
http://docs.seleniumhq.org/download/maven.jsp
I have maven installed and working.
I've copied the example pom.xml, changing only the project name
<?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>SeleniumTest</groupId>
<artifactId>SeleniumTest</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.44.0</version>
</dependency>
<dependency>
<groupId>com.opera</groupId>
<artifactId>operadriver</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.opera</groupId>
<artifactId>operadriver</artifactId>
<version>1.5</version>
<exclusions>
<exclusion>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-remote-driver</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</dependencyManagement>
</project>
Using
mvn clean install
runs without any errors. The target directory is created, containing SeleniumTest-1.0.jar and the maven-archiver directory. The problem is that my Eclipse project can't resolve the Selenium classes. I've copied the example Java driver class, modifying the imports based on my project layout:
import Selenium.*;
import Selenium.target.*;
public class Selenium2Example {
public static void main(String[] args) {
// Create a new instance of the Firefox driver
// Notice that the remainder of the code relies on the interface,
// not the implementation.
WebDriver driver = new FirefoxDriver();
// And now use this to visit Google
driver.get("http://www.google.com");
// Alternatively the same thing can be done like this
// driver.navigate().to("http://www.google.com");
// Find the text input element by its name
WebElement element = driver.findElement(By.name("q"));
// Enter something to search for
element.sendKeys("Cheese!");
// Now submit the form. WebDriver will find the form for us from the element
element.submit();
// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());
// Google's search is rendered dynamically with JavaScript.
// Wait for the page to load, timeout after 10 seconds
(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().startsWith("cheese!");
}
});
// Should see: "cheese! - Google Search"
System.out.println("Page title is: " + driver.getTitle());
//Close the browser
driver.quit();
}
}
The classes "WebDriver", "WebElement", "WebDriverWait", and "ExpectedCondition" can't be resolved. Trying to use the imports in the example
import Selenium.By;
import Selenium.WebDriver;
import Selenium.WebElement;
import Selenium.firefox.FirefoxDriver;
import Selenium.support.ui.ExpectedCondition;
import Selenium.support.ui.WebDriverWait;
all fail.
I looked into the jar downloaded by Maven, SeleniumTest-1.0.jar, and it is effectively empty. It only contains the META-INF directory.
I feel like I'm missing something obvious, but I just can't figure it out. I feel like I'm missing something in my pom.xml, but I can't find anything on Selenium's site that helps. Can anyone give me a hand?

Categories

Resources