simple JXLS / Apache POI example fails - java

I have no idea way I get this error. The code is from JXLS own example and the Jars are downloaded from there page.
Error code:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/poi/ss/usermodel/Workbook
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at org.jxls.util.TransformerFactory.loadPoiTransformer(TransformerFactory.java:85)
at org.jxls.util.TransformerFactory.getTransformerClass(TransformerFactory.java:69)
at org.jxls.util.TransformerFactory.createTransformer(TransformerFactory.java:27)
at org.jxls.util.JxlsHelper.createTransformer(JxlsHelper.java:250)
at org.jxls.util.JxlsHelper.processTemplate(JxlsHelper.java:108)
at test_excel.ObjectCollectionDemo.main(ObjectCollectionDemo.java:32)
Caused by: java.lang.ClassNotFoundException: org.apache.poi.ss.usermodel.Workbook
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 8 more
Referenced Libraries:
/slf4j-1.7.25/slf4j-api-1.7.25.jar
/slf4j-1.7.25/slf4j-jdk14-1.7.25.jar
/jxls-2.4.1 2/dist/jxls-reader-2.0.3.jar
/jxls-2.4.1 2/dist/jxls-poi-1.0.13.jar
/xls-2.4.1 2/dist/jxls-jexcel-1.0.6.jar
/jxls-2.4.1 2/dist/jxls-2.4.1.jar
Main code:
package test_excel;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class ObjectCollectionDemo {
private static Logger logger = LoggerFactory.getLogger(ObjectCollectionDemo.class);
public static void main(String[] args) throws ParseException, IOException {
logger.info("Running Object Collection demo");
List<Employee> employees = generateSampleEmployeeData();
try(InputStream is = ObjectCollectionDemo.class.getResourceAsStream("object_collection_template.xls")) {
try (OutputStream os = new FileOutputStream("object_collection_output.xls")) {
Context context = new Context();
context.putVar("employees", employees);
logger.info("OK so far...");
JxlsHelper.getInstance().processTemplate(is, os, context);
}
}
}
public static List<Employee> generateSampleEmployeeData() throws ParseException {
List<Employee> employees = new ArrayList<Employee>();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd", Locale.US);
employees.add( new Employee("Elsa", dateFormat.parse("1970-Jul-10"), 1500, 0.15) );
employees.add( new Employee("Oleg", dateFormat.parse("1973-Apr-30"), 2300, 0.25) );
employees.add( new Employee("Neil", dateFormat.parse("1975-Oct-05"), 2500, 0.00) );
employees.add( new Employee("Maria", dateFormat.parse("1978-Jan-07"), 1700, 0.15) );
employees.add( new Employee("John", dateFormat.parse("1969-May-30"), 2800, 0.20) );
return employees;
}
}

Looks like you need poi-3.XX.jar in your class path - see here.

Related

Testng + testrail integration. Failing at #BeforeMethod

I am trying to integrate testng with testrail but I am having a problem. Below the code is in my BaseTest. If I run testng on BaseTest it works and I see my result in testrail. If I move onboardingtest, changingToTest, and changingToAllListings to its own class, running testng will bomb the #BeforeMethod. I am not sure how to fix it. Can someone help? My guess is something wrong with #BeforeMethod. Maybe it shouldn't be Method m = BaseTest.class.getMethod(method.getName()); I have attached my error as well
package appiumStudio.appiumStudio;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import org.json.simple.JSONObject;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.annotations.*;
import api.APIException;
import api.APIClient;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.remote.AndroidMobileCapabilityType;
import io.appium.java_client.remote.MobileCapabilityType;
import pageObjects.Onboarding;
import pageObjects.Search;
import util.OnboardingFlow;
public class BaseTest {
protected static AndroidDriver<AndroidElement> driver = null;
String PROJECT_ID = "13";
APIClient client = null;
DesiredCapabilities dc = new DesiredCapabilities();
#BeforeSuite
public void createSuite(ITestContext ctx) throws MalformedURLException,IOException, APIException {
dc.setCapability(MobileCapabilityType.UDID, "6bf9c570");
dc.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, "com.test.buyerapp.staging");
dc.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, "com.tet.buyerapp.MainActivity");
driver = new AndroidDriver<AndroidElement>(new URL("http://localhost:4723/wd/hub"), dc);
driver.setLogLevel(Level.INFO);
client = new APIClient("https://test.testrail.io");
client.setUser("qa#test.com");
client.setPassword("password");
Map data = new HashMap();
data.put("include_all",true);
data.put("name","Test Run "+System.currentTimeMillis());
JSONObject c = null;
c = (JSONObject)client.sendPost("add_run/"+PROJECT_ID,data);
Long suite_id = (Long)c.get("id");
ctx.setAttribute("suiteId",suite_id);
driver.resetApp();
}
#BeforeMethod
public void beforeTest(ITestContext ctx,Method method) throws NoSuchMethodException {
Method m = BaseTest.class.getMethod(method.getName());
if (m.isAnnotationPresent(TestRails.class)) {
TestRails ta = m.getAnnotation(TestRails.class);
System.out.println(ta.id());
ctx.setAttribute("caseId",ta.id());
}
}
#TestRails(id="20178")
#Test(priority=1)
public void onboardingtest() throws InterruptedException {
OnboardingFlow.onboarding();
}
#TestRails(id="20176")
#Test(priority = 2)
public void changingToTest() throws InterruptedException {
Search.ToggleAllListings(driver).click();
new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#text='Every available home for sale']")));
Search.SelectTestHomes(driver).click();
new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#text='Self-tour Test homes']")));
Search.ClickGotIt(driver).click();
Thread.sleep(2000);
}
#TestRails(id="20177")
#Test(priority = 3)
public void changingToAllListings() {
Search.ToggleTestHomes(driver).click();
new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#text='Self-tour instantly with app unlock']")));
Search.SelectAllListings(driver).click();
new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#text='All listings']")));
}
#AfterMethod
public void afterTest(ITestResult result, ITestContext ctx) throws IOException, APIException {
Map data = new HashMap();
if(result.isSuccess()) {
data.put("status_id",1);
}
else {
data.put("status_id", 5);
data.put("comment", result.getThrowable().toString());
}
String caseId = (String)ctx.getAttribute("caseId");
Long suiteId = (Long)ctx.getAttribute("suiteId");
client.sendPost("add_result_for_case/"+suiteId+"/"+caseId,data);
}
#AfterClass
public void tearDown() {
driver.resetApp();
}
}
I get this error below whenI move onboardingtest, changingToTest, and changingToAllListings to its own class.
FAILED: beforeTest(org.testng.TestRunner#578524c3, public void searchHomeToggle.ToggleHome.beforeTest(org.testng.ITestContext,java.lang.reflect.Method) throws java.lang.NoSuchMethodException) java.lang.NoSuchMethodException: appiumStudio.appiumStudio.BaseTest.beforeTest()
at java.base/java.lang.Class.getMethod(Class.java:2114) at searchHomeToggle.ToggleHome.beforeTest(ToggleHome.java:23) 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:567) at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:133)
at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:584) at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:172) at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46) at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:804)
at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:145) at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146) at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128) at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
at org.testng.TestRunner.privateRun(TestRunner.java:770) at org.testng.TestRunner.run(TestRunner.java:591) at org.testng.SuiteRunner.runTest(SuiteRunner.java:402) at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:396) at org.testng.SuiteRunner.privateRun(SuiteRunner.java:355)
at org.testng.SuiteRunner.run(SuiteRunner.java:304) at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53) at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96) at org.testng.TestNG.runSuitesSequentially(TestNG.java:1180) at org.testng.TestNG.runSuitesLocally(TestNG.java:1102)
at org.testng.TestNG.runSuites(TestNG.java:1032) at org.testng.TestNG.run(TestNG.java:1000) at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115) at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251) at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)

Getting java.nio.file.AccessDeniedException , when trying to create zip file using java NIO 2 on MAC

import java.io.IOException;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.util.HashMap;
import java.util.Map;
public class ZipFileSystem {
public static void main(String[] args) throws IOException {
URI uri = URI.create("jar:file:///sample.zip");
Map<String,String> options = new HashMap<>();
options.put("create","true");
FileSystem fileSystem = FileSystems.newFileSystem(uri, options);
}
}
I have this java simple code , when i try to run this on MAC, getting below exception, am I missing anything?
Exception in thread "main" java.nio.file.AccessDeniedException: /sample.zip
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:84)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
at sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:214)
at java.nio.file.spi.FileSystemProvider.newOutputStream(FileSystemProvider.java:434)
at java.nio.file.Files.newOutputStream(Files.java:216)
at com.sun.nio.zipfs.ZipFileSystem.<init>(ZipFileSystem.java:116)
at com.sun.nio.zipfs.ZipFileSystemProvider.newFileSystem(ZipFileSystemProvider.java:117)
at java.nio.file.FileSystems.newFileSystem(FileSystems.java:326)
at java.nio.file.FileSystems.newFileSystem(FileSystems.java:276)
at ZipFileSystem.main(ZipFileSystem.java:14)

Spark Throwing a "NoClassDefFoundError" Despite jar Indicating Class is Present

I am receiving a NoClassDefFoundError despite 7Zip indicating the jar containing the class is present in the uberjar being submitted to run the program. I am submitting with the below line:
spark-submit --class org.dia.red.ctakes.spark.CtakesSparkMain target/spark-ctakes-0.1-job.jar
The error being thrown is:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/uima/cas/FSIndex
at org.dia.red.ctakes.spark.CtakesSparkMain.main(CtakesSparkMain.java:50)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:743)
at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:187)
at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:212)
at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:126)
at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.lang.ClassNotFoundException: org.apache.uima.cas.FSIndex
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 10 more
The CtakesSparkMain class below calls the CtakesFunction class:
package org.dia.red.ctakes.spark;
import java.util.List;
import java.io.PrintWriter;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.uima.jcas.cas.FSArray;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.storage.StorageLevel;
import org.json.JSONObject;
public class CtakesSparkMain {
/**
* #param args
*/
public static void main(String[] args) throws Exception {
SparkConf conf = new SparkConf().setAppName("ctakes");
JavaSparkContext sc = new JavaSparkContext(conf);
JavaRDD<String> lines = sc.textFile("/mnt/d/metistream/ctakes-streaming/SparkStreamingCTK/testdata100.txt").map(new CtakesFunction());
String first = lines.take(2).get(0);
PrintWriter out = new PrintWriter("/mnt/d/metistream/ctakes-streaming/SparkStreamingCTK/test_outputs/output.txt");
out.println(first);
out.close();
sc.close();
}
}
CtakesFunction:
package org.dia.red.ctakes.spark;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import org.apache.ctakes.typesystem.type.refsem.OntologyConcept;
import org.apache.ctakes.typesystem.type.textsem.*;
import org.apache.uima.UIMAException;
import org.apache.uima.cas.FSIndex;
import org.apache.uima.cas.Type;
import org.apache.uima.UIMAException;
import org.apache.uima.jcas.JCas;
import org.apache.uima.analysis_engine.AnalysisEngineDescription;
import org.apache.uima.cas.impl.XmiCasSerializer;
import org.apache.uima.fit.factory.JCasFactory;
import org.apache.uima.fit.pipeline.SimplePipeline;
import org.apache.uima.jcas.cas.FSArray;
import org.apache.uima.util.XMLSerializer;
import org.apache.spark.api.java.function.Function;
import it.cnr.iac.CTAKESClinicalPipelineFactory;
import org.json.*;
/**
* #author Selina Chu, Michael Starch, and Giuseppe Totaro
*
*/
public class CtakesFunction implements Function<String, String> {
transient JCas jcas = null;
transient AnalysisEngineDescription aed = null;
private void setup() throws UIMAException {
System.setProperty("ctakes.umlsuser", "");
System.setProperty("ctakes.umlspw", "");
this.jcas = JCasFactory.createJCas();
this.aed = CTAKESClinicalPipelineFactory.getDefaultPipeline();
}
private void readObject(ObjectInputStream in) {
try {
in.defaultReadObject();
this.setup();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UIMAException e) {
e.printStackTrace();
}
}
#Override
public String call(String paragraph) throws Exception {
this.jcas.setDocumentText(paragraph);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
SimplePipeline.runPipeline(this.jcas, this.aed);
FSIndex index = this.jcas.getAnnotationIndex(IdentifiedAnnotation.type);
Iterator iter = index.iterator();
JSONArray annotationsArray = new JSONArray();
JSONObject allAnnotations = new JSONObject();
ArrayList<String> types = new ArrayList<String>();
types.add("org.apache.ctakes.typesystem.type.textsem.SignSymptomMention");
types.add("org.apache.ctakes.typesystem.type.textsem.DiseaseDisorderMention");
types.add("org.apache.ctakes.typesystem.type.textsem.AnatomicalSiteMention");
types.add("org.apache.ctakes.typesystem.type.textsem.ProcedureMention");
types.add("import org.apache.ctakes.typesystem.type.textsem.MedicationMention");
String type;
String[] splitType;
FSArray snomedArray;
ArrayList<String> snomedStringArray = new ArrayList<String>();
while (iter.hasNext()){
IdentifiedAnnotation annotation = (IdentifiedAnnotation)iter.next();
type = annotation.getType().toString();
if (types.contains(type)){
JSONObject annotations = new JSONObject();
splitType = type.split("[.]");
annotations.put("id", annotation.getId());
annotations.put("subject", annotation.getSubject());
annotations.put("type", splitType[splitType.length - 1]);
annotations.put("text", annotation.getCoveredText());
annotations.put("polarity", annotation.getPolarity());
annotations.put("confidence", annotation.getConfidence());
snomedArray = annotation.getOntologyConceptArr();
for (int i = 0; i < snomedArray.size(); i++){
snomedStringArray.add(((OntologyConcept)snomedArray.get(i)).getCode());
}
annotations.put("snomed_codes", snomedStringArray);
snomedStringArray.clear();
annotationsArray.put(annotations);
}
}
allAnnotations.put("Annotations", annotationsArray);
this.jcas.reset();
return allAnnotations.toString();
}
}
I was attempting to modify the repository # https://github.com/selinachu/SparkStreamingCTK to leverage regular Spark as opposed to SparkStreaming (and Spark 2.0), but haven't been able to resolve this.
This is because this is not entirely an uber-jar generated by maven for this project. Spark-submit can not load a class from a jar within a jar. One need a special class loader for this. The right approach would be to explode all jars to put all contained classes in the uber-jar similar how maven shade plugin does it https://maven.apache.org/plugins/maven-shade-plugin/
So you have to change pom.xml file to generate correct uber-jar for this project.
Inspired by YuGagarin's feedback, I used SBT assembly to assemble an UberJar of cTAKES itself. Compiling everything into one "true" fat jar resolved the above issue.
However, I should point out there are still some residual issues with cTAKES and Spark that I am currently working through.

How to fix Saml assertion Exception (NoClassDefFoundError)

Hi guys i've created a saml assertion with opensaml-j and when i run the program an exception occurs and throws NoClassDefFoundError
i've loaded all the necessary jar files but still don't work
here's my code:
package memory;
import java.security.SecureRandom;
import org.joda.time.DateTime;
import org.opensaml.saml.common.SAMLVersion;
import org.opensaml.saml.saml1.core.AttributeStatement;
import org.opensaml.saml.saml1.core.AttributeValue;
import org.opensaml.saml.saml1.core.NameIdentifier;
import org.opensaml.saml.saml1.core.Subject;
import org.opensaml.saml.saml1.core.impl.EvidenceBuilder;
import org.opensaml.saml.saml1.core.impl.NameIdentifierBuilder;
import org.opensaml.saml.saml1.core.impl.SubjectBuilder;
import org.opensaml.saml.saml2.core.Action;
import org.opensaml.saml.saml2.core.Assertion;
import org.opensaml.saml.saml2.core.Attribute;
import org.opensaml.saml.saml2.core.AuthzDecisionStatement;
import org.opensaml.saml.saml2.core.Conditions;
import org.opensaml.saml.saml2.core.DecisionTypeEnumeration;
import org.opensaml.saml.saml2.core.Evidence;
import org.opensaml.saml.saml2.core.Issuer;
import org.opensaml.saml.saml2.core.impl.ActionBuilder;
import org.opensaml.saml.saml2.core.impl.AssertionBuilder;
import org.opensaml.saml.saml2.core.impl.AttributeBuilder;
import org.opensaml.saml.saml2.core.impl.AttributeStatementBuilder;
import org.opensaml.saml.saml2.core.impl.AuthzDecisionStatementBuilder;
import org.opensaml.saml.saml2.core.impl.ConditionsBuilder;
import org.opensaml.saml.saml2.core.impl.IssuerBuilder;
public class CreateSamlAssertion {
#SuppressWarnings("deprecation")
public static Assertion createAssertion(){
Assertion assertion=(Assertion)new AssertionBuilder().buildObject();
assertion.setID(idGenerator());
assertion.setVersion(SAMLVersion.VERSION_20);
assertion.setIssueInstant(new DateTime());
Issuer issuer=(Issuer)new IssuerBuilder().buildObject();
issuer.setNameQualifier("bob");
assertion.setIssuer(issuer);
Subject subject=(Subject)new SubjectBuilder().buildObject();
NameIdentifier nameId=(NameIdentifier)new NameIdentifierBuilder().buildObject();
nameId.setFormat(NameIdentifier.EMAIL);
nameId.setNameIdentifier("alice");
subject.setNameIdentifier(nameId);
Conditions conditions=(Conditions)new ConditionsBuilder().buildObject();
conditions.setNotBefore(new DateTime());
conditions.setNotOnOrAfter(new DateTime().plusMinutes(20));
assertion.setConditions(conditions);
AuthzDecisionStatement authDecisionStatement=getAuthzDecisionStatement();
assertion.getAuthzDecisionStatements().add(authDecisionStatement);
return assertion;
}
private static AuthzDecisionStatement getAuthzDecisionStatement(){
AuthzDecisionStatement aDStatement=(AuthzDecisionStatement)new AuthzDecisionStatementBuilder().buildObject();
DecisionTypeEnumeration decision = DecisionTypeEnumeration.PERMIT;
aDStatement.setDecision(decision);
aDStatement.setResource("http://www.hb.com/Resources/Resource A1");
Action actions=getAction();
actions.setNamespace("http://www.hb.com/Resources/");
aDStatement.getActions().add(actions);
Evidence evidence=getEvidence();
aDStatement.setEvidence(evidence);
return aDStatement;
}
private static Evidence getEvidence(){
Evidence evidence=(Evidence)new EvidenceBuilder().buildObject();
Assertion assertion=(Assertion)new AssertionBuilder().buildObject();
AttributeStatement aStatement=(AttributeStatement) new AttributeStatementBuilder().buildObject();
Attribute attribute1=(Attribute)new AttributeBuilder().buildObject();
attribute1.setName("IssuerCapabilityID");
AttributeValue aValue1=(AttributeValue) AttributeValue.DEFAULT_ELEMENT_NAME;
attribute1.getAttributeValues().add(aValue1);
Attribute attribute2=(Attribute)new AttributeBuilder().buildObject();
attribute2.setName("IssuerCapabilityID");
AttributeValue aValue2=(AttributeValue) AttributeValue.DEFAULT_ELEMENT_NAME;
attribute1.getAttributeValues().add(aValue2);
aStatement.getAttributes().add((org.opensaml.saml.saml1.core.Attribute) attribute1);
aStatement.getAttributes().add((org.opensaml.saml.saml1.core.Attribute) attribute2);
assertion.getAttributeStatements().add((org.opensaml.saml.saml2.core.AttributeStatement) aStatement);
evidence.getAssertions().add(assertion);
return evidence;
}
private static Action getAction(){
Action action=(Action)new ActionBuilder().buildObject();
action.setAction("Read");
action.setAction("Write");
return action;
}
private static String idGenerator(){
SecureRandom random=new SecureRandom();
return String.valueOf(random.nextInt());
}
}
and here's the main class:
package memory;
import org.opensaml.saml.saml2.core.Assertion;
public class SamlTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Assertion assertion=CreateSamlAssertion.createAssertion();
System.out.println(assertion);
}
}
the stack trace
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at org.opensaml.core.xml.AbstractXMLObject.<init>(AbstractXMLObject.java:47)
at org.opensaml.xmlsec.signature.AbstractSignableXMLObject.<init>(AbstractSignableXMLObject.java:47)
at org.opensaml.saml.common.AbstractSignableSAMLObject.<init>(AbstractSignableSAMLObject.java:44)
at org.opensaml.saml.saml2.core.impl.AssertionImpl.<init>(AssertionImpl.java:83)
at org.opensaml.saml.saml2.core.impl.AssertionBuilder.buildObject(AssertionBuilder.java:45)
at org.opensaml.saml.saml2.core.impl.AssertionBuilder.buildObject(AssertionBuilder.java:40)
at memory.CreateSamlAssertion.createAssertion(CreateSamlAssertion.java:34)
at memory.SamlTest.main(SamlTest.java:9)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
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)
... 8 more
and thanks in advance

Test passed in IDE but failed in TeamCity

I have a class that i had to test:
package com.mycompany.openapi.cms.core.support.liquibase;
import liquibase.change.custom.CustomTaskChange;
import liquibase.database.Database;
import liquibase.database.jvm.JdbcConnection;
import liquibase.exception.CustomChangeException;
import liquibase.exception.SetupException;
import liquibase.exception.ValidationErrors;
import liquibase.resource.ResourceAccessor;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Statement;
import java.util.Set;
public class ApplySqlFileIfExistsChange implements CustomTaskChange {
private final org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());
private String file;
private ResourceAccessor resourceAccessor;
#Override
public void execute(Database database) throws CustomChangeException {
JdbcConnection databaseConnection = (JdbcConnection) database.getConnection();
try {
Set<InputStream> files = resourceAccessor.getResourcesAsStream(file);
if(files != null){
for (InputStream inputStream : files) {
BufferedReader in = new BufferedReader(
new InputStreamReader(inputStream));
String str;
String sql;
StringBuilder sqlBuilder = new StringBuilder("");
while ((str = in.readLine()) != null) {
sqlBuilder.append(str).append(" ");
}
in.close();
sql = sqlBuilder.toString().trim();
if(StringUtils.isEmpty(sql)){
return;
}
Statement statement = databaseConnection.createStatement();
statement.execute(sql);
statement.close();
}
}
} catch (FileNotFoundException e) {
logger.error(e.getMessage(), e);
} catch (Exception e) {
throw new CustomChangeException(e);
}
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
#Override
public void setFileOpener(ResourceAccessor resourceAccessor) {
this.resourceAccessor = resourceAccessor;
}
}
I had written the test:
package com.mycompany.openapi.cms.core.support.liquibase;
import com.google.common.collect.Sets;
import liquibase.database.Database;
import liquibase.database.jvm.JdbcConnection;
import liquibase.resource.ResourceAccessor;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Statement;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.*;
#RunWith(PowerMockRunner.class)
#PrepareForTest({LoggerFactory.class})
public class TestApplySqlFileIfExistsChange {
#InjectMocks
ApplySqlFileIfExistsChange applySqlFileIfExistsChange;
#Mock
private ResourceAccessor resourceAccessor;
#Mock
private JdbcConnection jdbcConnection;
#Mock
private Database database;
#Mock
Statement statement;
#BeforeClass
public static void setUpClass() {
mockStatic(LoggerFactory.class);
when(LoggerFactory.getLogger(ApplySqlFileIfExistsChange.class)).thenReturn(mock(Logger.class));
}
#Before
public void setUp() throws Exception {
when(database.getConnection()).thenReturn(jdbcConnection);
InputStream inp1, inp2;
inp1 = new ByteArrayInputStream("FirstTestQuery".getBytes(StandardCharsets.UTF_8));
inp2 = new ByteArrayInputStream("SecondTestQuery".getBytes(StandardCharsets.UTF_8));
when(resourceAccessor.getResourcesAsStream(anyString())).thenReturn(Sets.newHashSet(inp1, inp2));
when(jdbcConnection.createStatement()).thenReturn(statement);
}
#Test
public void execute() throws Exception {
applySqlFileIfExistsChange.execute(database);
verify(statement).execute("FirstTestQuery");
verify(statement).execute("SecondTestQuery");
}
}
Problem is that test above passed in my IDE, but when i make push in repository TeamCity build failed on my test. I can't undestand why, because code are same in both places. Here is stack trace in TeamCity:
java.lang.IllegalStateException: Failed to transform class with name org.slf4j.LoggerFactory. Reason: java.io.IOException: invalid constant type: 15
at org.powermock.core.classloader.MockClassLoader.loadMockClass(MockClassLoader.java:267)
at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:180)
at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:70)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType(CoreReflectionFactory.java:114)
at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:125)
at sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49)
at sun.reflect.annotation.AnnotationParser.parseSig(AnnotationParser.java:439)
at sun.reflect.annotation.AnnotationParser.parseClassValue(AnnotationParser.java:420)
at sun.reflect.annotation.AnnotationParser.parseClassArray(AnnotationParser.java:724)
at sun.reflect.annotation.AnnotationParser.parseArray(AnnotationParser.java:531)
at sun.reflect.annotation.AnnotationParser.parseMemberValue(AnnotationParser.java:355)
at sun.reflect.annotation.AnnotationParser.parseAnnotation2(AnnotationParser.java:286)
at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:120)
at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:72)
at java.lang.Class.createAnnotationData(Class.java:3521)
at java.lang.Class.annotationData(Class.java:3510)
at java.lang.Class.getAnnotation(Class.java:3415)
at org.junit.internal.MethodSorter.getDeclaredMethods(MethodSorter.java:52)
at org.junit.internal.runners.TestClass.getAnnotatedMethods(TestClass.java:45)
at org.junit.internal.runners.MethodValidator.validateTestMethods(MethodValidator.java:71)
at org.junit.internal.runners.MethodValidator.validateStaticMethods(MethodValidator.j
I apologize for such a number of code in my question.
You probably have conflicting Powermock/Mockito versions.
Check your local maven repo for the versions, and get rid of the older ones
in your pom and/or update the other dependency which included it.
Check in the root of the project with:
mvn dependency:tree -Dverbose -Dincludes=NAME_OF_DEPENDENCY
You have a conflict of dependent libraries in the TeamCity repo vs your local repo.
Confirm the TC build is using the exact same version of Powermock that your local is using.
There may be an older version being transitively included.
mvn dependency:tree -Dverbose
This will list all the resolvable dependencies. See if there are different versions of Powermock. You can then stop them being possible pulled in by using the exclude/exclusions tag in the pom.xml.

Categories