json-schema-validator NoClassDefFoundError: com/google/common/io/Closer - java

Solution: Add the guava dependency:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
I'm trying to use the json-schema-validator over here: https://github.com/fge/json-schema-validator .
I'm using the following maven dependency:
<dependency>
<groupId>com.github.fge</groupId>
<artifactId>json-schema-validator</artifactId>
<version>2.2.5</version>
</dependency>
Here is a class I'm trying:
import java.io.IOException;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.JsonLoader;
public class JsonSchemaTest {
public static void main(String[] args) throws IOException {
JsonNode jsonNode = JsonLoader.fromString("{\"a\":1}");
}
}
And here is the error I'm receiving:
Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/io/Closer
at com.github.fge.jackson.JsonNodeReader.fromReader(JsonNodeReader.java:120)
at com.github.fge.jackson.JsonLoader.fromReader(JsonLoader.java:179)
at com.github.fge.jackson.JsonLoader.fromString(JsonLoader.java:192)
at com.cisco.webex.squared.flume.JsonSchemaTest.main(JsonSchemaTest.java:10)
Caused by: java.lang.ClassNotFoundException: com.google.common.io.Closer
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
... 4 more
--- Edit:
If I change my maven version to 2.1.7, I can do JsonNode jsonNode = JsonLoader.fromString("{\"a\":1}"); but I cannot create the factory here without the same java.lang.NoClassDefFoundError: com/google/common/io/Closer error:
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.JsonLoader;
import com.github.fge.jsonschema.exceptions.ProcessingException;
import com.github.fge.jsonschema.main.JsonSchema;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.github.fge.jsonschema.report.ProcessingReport;
public final class JsonSchemaTest {
public static void main(final String[] args) throws IOException, ProcessingException {
//JsonNode data = JsonLoader.fromString("{\"a\":1}");
final JsonNode data = JsonLoader.fromString("{\"a\":1}");
final JsonNode fstabSchema = JsonLoader.fromString("{\"type\":\"object\", \"properties\":{\"a\":{\"type\":\"number\"}}}");
final JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
final JsonSchema schema = factory.getJsonSchema(fstabSchema);
ProcessingReport report;
report = schema.validate(data);
System.out.println(report);
}
}

You have to import guava library in your project.
http://www.java2s.com/Code/Jar/g/Downloadguava150rc1jar.htm

Related

Parsing xml file with JAXB

I'm implementing a simple xml parser and faced with a problem:
exception is thrown when initialising JAXBContext.
Here is my code(maybe too much for this question, but I've tried to include only important parts):
Parser itself:
package com.andreiyusupau.jaxbparser.parser;
import com.andreiyusupau.jaxbparser.model.Parent;
import com.andreiyusupau.jaxbparser.model.Root;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.util.Collection;
public class JaxbParser {
public Collection<Parent> parse(String inputXml) throws JAXBException {
JAXBContext jc = JAXBContext.newInstance(Root.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Root root = (Root) unmarshaller.unmarshal(new File(inputXml));
return root.getElements();
}
}
Main:
public class Main {
public static final String FILE_NAME = "data.xml";
public static void main(String[] args) throws JAXBException {
JaxbParser jaxbParser = new JaxbParser();
Collection<Parent> elements= jaxbParser.parse(FILE_NAME);
for (Parent element : elements) {
System.out.println(element.toString());
}
}
}
Classes (getters,setters and toString are hidden):
import javax.xml.bind.annotation.*;
import java.util.List;
#XmlRootElement(name = "root")
#XmlAccessorType(XmlAccessType.FIELD)
public class Root {
#XmlElements({
#XmlElement(name = "ChildA", type = ChildA.class),
#XmlElement(name = "ChildB", type = ChildB.class),
})
private List<Parent> elements;
public Root() {
}
}
import org.eclipse.persistence.oxm.annotations.XmlPath;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlTransient;
#XmlTransient
#XmlSeeAlso({ChildA.class, ChildB.class})
public class Parent {
#XmlAttribute
private int id;
#XmlElement(name = "name")
private String name;
#XmlElement(name = "parameter")
private String parameter;
#XmlPath("parameter/#parameterAttr")
private String parameterAttribute;
#XmlPath("similar/a/text()")
private int a;
#XmlPath("similar/b/text()")
private int b;
#XmlPath("different/similar/text()")
private String similar;
#XmlPath("different/similar/#similarAttr")
private String similarAttribute;
public Parent() {
}
}
import org.eclipse.persistence.oxm.annotations.XmlPath;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "childA")
public class ChildA extends Parent {
#XmlPath("different/differentA/text()")
private String differentA;
#XmlPath("different/differentA/#attrA")
private String differentAttributeA;
public ChildA() {
}
}
import org.eclipse.persistence.oxm.annotations.XmlPath;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "childB")
public class ChildB extends Parent {
#XmlPath("different/differentB1/text()")
private String differentB1;
#XmlPath("different/differentB1/#attrB1")
private String differentAttributeB1;
#XmlPath("different/differentB2/text()")
private String differentB2;
#XmlPath("different/differentB2/#attrB2")
private String differentAttributeB2;
public ChildB() {
}
}
and finally an xml file itself:
<?xml version="1.1" encoding="UTF-8"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation = "schema.xsd">
<childA id="ID-1">
<name>Name</name>
<parameter parameterAttr="a">b</parameter>
<similarGroup>
<a>1</a>
<b>2</b>
</similarGroup>
<different>
<similar similarAttr="n">2</similar>
<differentA attrA="n">100</differentA>
</different>
</childA>
<childB id="ID-2">
<name>Name</name>
<parameter parameterAttr="c">d</parameter>
<similarGroup>
<a>6</a>
<b>8</b>
</similarGroup>
<different>
<similar similarAttr="g">7</similar>
<differentB1 attrB1="5">100</differentB1>
<differentB2>100</differentB2>
</different>
</childB>
</root>
and dependencies in POM xml:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>3.0.0-M1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.3</version>
</dependency>
jaxb.properties
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Compiling and running this code gives the following exception:
Exception in thread "main" java.lang.NoClassDefFoundError: jakarta/xml/bind/JAXBContext
at java.base/java.lang.Class.getDeclaredMethods0(Native Method)
at java.base/java.lang.Class.privateGetDeclaredMethods(Class.java:3166)
at java.base/java.lang.Class.getMethodsRecursive(Class.java:3307)
at java.base/java.lang.Class.getMethod0(Class.java:3293)
at java.base/java.lang.Class.getMethod(Class.java:2106)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:249)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:240)
at javax.xml.bind.ContextFinder.find(ContextFinder.java:345)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:691)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:632)
at com.andreiyusupau.jaxbparser.parser.JaxbParser.parse(JaxbParser.java:15)
at com.andreiyusupau.jaxbparser.Main.main(Main.java:15)
Caused by: java.lang.ClassNotFoundException: jakarta.xml.bind.JAXBContext
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
... 12 more
Maybe someone knows how can I solve it?
UPDATE:
After replacing jakarta.xml.bind-api with jaxb-api I have the following exception:
Exception in thread "main" javax.xml.bind.JAXBException: ClassCastException: attempting to cast jar:file:/C:/Users/Nevermind/.m2/repository/javax/xml/bind/jaxb-api/2.3.1/jaxb-api-2.3.1.jar!/javax/xml/bind/JAXBContext.class to jar:file:/C:/Users/Nevermind/.m2/repository/javax/xml/bind/jaxb-api/2.3.1/jaxb-api-2.3.1.jar!/javax/xml/bind/JAXBContext.class. Please make sure that you are specifying the proper ClassLoader.
at javax.xml.bind.ContextFinder.handleClassCastException(ContextFinder.java:157)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:300)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:286)
at javax.xml.bind.ContextFinder.find(ContextFinder.java:391)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:721)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:662)
at com.andreiyusupau.jaxbparser.parser.JaxbParser.parse(JaxbParser.java:15)
at com.andreiyusupau.jaxbparser.Main.main(Main.java:15)
The exception is thrown in line:
JAXBContext jc = JAXBContext.newInstance(Root.class);
Any suggestions?
I suggest replace dependency
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.3</version>
</dependency>
with
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
jakarta.xml.bind comes from Jakarta EE and org.glassfish.jaxb comes from older Java EE.
Do mvn dependency:tree (or mvn help:effective-pom) to see which dependencies end up on your classpath.
Try using these:
<!-- XML -->
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<scope>runtime</scope>
<version>2.3.3</version>
</dependency>
All legacy JavaEE javax.* API's are being cleaned up by JakartaEE and released again as jakarta.* API's with proper maven metadata.

RestAssured_Class Not Found_com/github/fge/jsonschema/main/JsonSchemaFactory

Please help me with validating schema of the response body. I am facing a runtime error.:
Exception in thread "main" java.lang.NoClassDefFoundError:
com/github/fge/jsonschema/main/JsonSchemaFactory
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import io.restassured.response.ValidatableResponse;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
import static io.restassured.RestAssured.*;
public class Sample_JsonSchemaValidation {
public static void main(String[] args) {
// TODO Auto-generated method stub
//ClassLoader loader = Sample_JsonSchemaValidation.class.getClassLoader();
//System.out.println(loader.getResource("Sample_JsonSchemaValidation.class"));
RestAssured.baseURI = "https://reqres.in/";
given().contentType(ContentType.JSON).queryParam("id", 2).
when().get("api/users/"). then().body(matchesJsonSchemaInClasspath("JsonSchemavalidator.json"));
}
}
Please help resolve the error.
Do you have the below in your POM ?
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>4.3.0</version>
</dependency>
The compile dependencies include 2 artifacts, If you do not have them then include those as well in your POM
<dependency>
<groupId>com.github.java-json-tools</groupId>
<artifactId>json-schema-validator</artifactId>
<version>2.2.10</version>
</dependency>

Java reading an Excel file

I believe i have all the jar files I need and i'm still getting an error that says Caused by:
java.lang.reflect.InvocationTargetException
And forgive me, i'm still not wonderful at reading error messages. The error suggests the issue is with the line "Workbook book = new XSSFWorkbook(stream);"
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class excelReader {
public static void main(String[] args) throws IOException{
String spreadSheetFilePath = "C:\\Users\\userExample\\Documents\\forJava.xlsx";
FileInputStream stream = new FileInputStream(new File(spreadSheetFilePath));
Workbook book = new XSSFWorkbook(stream);
Sheet sheetOne = book.getSheetAt(0);
Iterator<Row> iterator = sheetOne.iterator();
while(iterator.hasNext()) {
Row nextRow = iterator.next();
Iterator<Cell> cellIter = nextRow.cellIterator();
while(cellIter.hasNext()) {
Cell cell = cellIter.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue());
break;
}
System.out.print(" - ");
}
System.out.println();
}
book.close();
stream.close();
}
}
Error i'm getting
Exception in thread "main" org.apache.poi.POIXMLException: java.lang.reflect.InvocationTargetException
at org.apache.poi.POIXMLFactory.createDocumentPart(POIXMLFactory.java:65)
at org.apache.poi.POIXMLDocumentPart.read(POIXMLDocumentPart.java:601)
at org.apache.poi.POIXMLDocument.load(POIXMLDocument.java:174)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:279)
at excelReader.main(excelReader.java:18)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.apache.poi.xssf.usermodel.XSSFFactory.createDocumentPart(XSSFFactory.java:56)
at org.apache.poi.POIXMLFactory.createDocumentPart(POIXMLFactory.java:62)
... 4 more
Caused by: java.lang.NoSuchMethodError: org.apache.xmlbeans.XmlOptions.setLoadEntityBytesLimit(I)Lorg/apache/xmlbeans/XmlOptions;
at org.apache.poi.POIXMLTypeLoader.<clinit>(POIXMLTypeLoader.java:50)
at org.apache.poi.xssf.model.ThemesTable.<init>(ThemesTable.java:85)
... 10 more
Jar files in my Library for project:
commons-codec-1.10.jar
commons-logging1-2.jar
dom4j-1.1.jar
junit-4.1.2.17.jar
poi-3.14-20160307.jar
poi-excelant-3.14-20160307.jar
poi-ooxml-schemas-3.14-20160307.jar
poi-scratchpad-3.14-20160307.jar
xmlbeans-2.3.0.jar
If you look at the StackTrace you can find that the exception is caused by :
java.lang.NoSuchMethodError: org.apache.xmlbeans.XmlOptions.setLoadEntityBytesLimit(I)Lorg/apache/xmlbeans/XmlOptions;
based on that I think you need the : xmlbeans-xmlpublic-2.6.0.jar inside your class path, try to add this additional jar into the class path and try again ...
I suggest to manage the dependency using Maven, that will simplify everything, just switch to maven and add the following lines to your pom file :
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>

read simple json lib file

Today I started learning about json files and I made a test using NetBeans and json-lib :
package tp;
import java.io.FileInputStream;
import java.io.IOException;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils;
public class Tp {
public static void main(String[] args) throws IOException {
String jsonTxt = IOUtils.toString(new FileInputStream("test/test/test1.json"), "UTF-8");
System.out.println("jsonTxt.length " + jsonTxt.length());
JSONArray root = (JSONArray) JSONSerializer.toJSON(jsonTxt);
JSONObject document = root.getJSONObject(0);
String tag = document.getString("tag");
System.out.println("tag " + tag);
}
}
this is my json file :
{
"tag": "value"
}
I'm tying to read and display the value but I get :
jsonTxt.length 25
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang/exception/NestableRuntimeException
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:455)
at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:367)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at tp.Tp.main(Tp.java:15)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang.exception.NestableRuntimeException
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 13 more
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
line 15 is : JSONArray root = (JSONArray) JSONSerializer.toJSON(jsonTxt);
What m'I doing wrong ?
SOLUTION :
adding all the libraries : commons-io-2.4.jar, ezmorph-1.0.6.jar, json-lib-2.4-jdk15.jar, commons-logging-1.2.jar, commons-lang-2.6.jar, commons-beanutils-1.9.2.jar, commons-collections-3.2.1.jar
package tp;
import java.io.FileInputStream;
import java.io.IOException;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils;
public class Tp {
public static void main(String[] args) throws IOException {
String jsonTxt = IOUtils.toString(new FileInputStream("test/test/test1.json"), "UTF-8");
System.out.println("jsonTxt.length " + jsonTxt.length());
JSONObject root = (JSONObject) JSONSerializer.toJSON(jsonTxt);
String tag = root.getString("tag");
System.out.println("tag " + tag);
}
}
Thanks

Getting NoClassDef Error for classes imported through Maven

I have a Maven project in Eclipse created through m2e. It obtains client libraries from a project on GitHub called alternator. The classes seem to be imported fine, in my project, but on running them, it shows a NoClassDefFound error. Here's the code and the error:
Code:
public class Main{
private AlternatorDBClient client;
private DynamoDBMapper mapper;
private AlternatorDB db;
public static void main(String args[]) throws Exception{
new Main().run();
}
public void run() throws Exception {
this.client = new AlternatorDBClient();
this.mapper = new DynamoDBMapper(this.client);
this.db = new AlternatorDB().start();
}
}
Error:
Exception in thread "main" java.lang.NoClassDefFoundError: com/michelboudreau/alternator/AlternatorDBClient
at Main.run(Main.java:17)
at Main.main(Main.java:13)
Caused by: java.lang.ClassNotFoundException: com.michelboudreau.alternator.AlternatorDBClient
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 2 more
The AlternatorDBClient class is importing one or more classes which are not on your class path:
import com.amazonaws.*;
import com.amazonaws.handlers.HandlerChainFactory;
import com.amazonaws.http.ExecutionContext;
import com.amazonaws.http.HttpResponseHandler;
import com.amazonaws.http.JsonErrorResponseHandler;
import com.amazonaws.http.JsonResponseHandler;
import com.amazonaws.services.dynamodb.AmazonDynamoDB;
import com.amazonaws.services.dynamodb.model.*;
import com.amazonaws.services.dynamodb.model.transform.*;
import com.amazonaws.transform.JsonErrorUnmarshaller;
import com.amazonaws.transform.JsonUnmarshallerContext;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.util.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
You are somehow missing:
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
</dependency>
as a dependency in your project pom. As AlexR stated, please post your pom.

Categories