I need to use JUnitCore to run unit tests from a standalone jar test tool. I have added the surefire jars as dependencies and there I found the class org.apache.maven.surefire.junitcore.JUnitCoreRunListener. In this github this is a sample of its usage.
My intention is to get the xml report that would result from running maven without maven at runtime.
RunListener reporter = new JUnitCoreRunListener( new MockReporter(), new HashMap<String, TestSet>() );
JUnitCore jc = new JUnitCore();
jc.addListener( reporter );
Result r = jc.run( new Computer(), AppTest.class);
jc.removeListener( reporter );
System.out.println( r );
This is not working. What is the correct approach to get the XML output from that reporter?
Related
I'm creating a Maven Skin (see https://maven.apache.org/doxia/doxia-sitetools/doxia-site-renderer/).
My site.vm needs to highlight links in a nav bar if the link is the current file being rendered.
I therefore need to know the name of the HTML file that site.vm is rendering.
The $currentFileName and $alignedFileName macros work just fine for regular documents (from Markdown source, for example). But for multi-pages documents, like a Maven Report plugin would generate, these macros keep returning the name of main page of the report, rather than the page being rendered.
How to retrieve the actual name of the file being rendered, and not just the name of the main HTML page of a Maven Report plugin?
I tried the following macros with no luck:
$alignedFileName
$currentFileName
$docRenderingContext.getInputName()
$docRenderingContext.getOutputName()
They all return the same value, which is the HTML filename of the main page of the Maven Report plugin.
KmReference.java (Maven Report plugin, creating several pages with getSinkFactory().createSink(outputDirectory, pageFilename)):
public class KmReference extends AbstractMavenReport {
public String getOutputName() {
return "km-reference";
}
…
#Override
protected void executeReport(Locale locale) throws MavenReportException {
…
// Create a new sink!
Sink kmSink;
try {
kmSink = getSinkFactory().createSink(outputDirectory, pageFilename);
} catch (IOException e) {
throw new MavenReportException("Could not create sink for " + pageFilename + " in " + outputDirectory.getAbsolutePath(), e);
}
site.vm (Velocity):
alignedFileName = $alignedFileName
currentFileName = $currentFileName
getDoxiaSourcePath() = $docRenderingContext.getDoxiaSourcePath()
getGenerator() = $docRenderingContext.getGenerator()
getInputName() = $docRenderingContext.getInputName()
getOutputName() = $docRenderingContext.getOutputName()
getParserId() = $docRenderingContext.getParserId()
getRelativePath() = $docRenderingContext.getRelativePath()
In all HTML files generated by my Maven Report plugin, I will get the exact same values:
another-page.html (not km-reference.html):
alignedFileName = km-reference.html
currentFileName = km-reference.html
getDoxiaSourcePath() = $docRenderingContext.getDoxiaSourcePath()
getGenerator() = com.sentrysoftware.maven:patrolreport-maven-plugin:2.0:km-reference
getInputName() = km-reference.html
getOutputName() = km-reference.html
getParserId() = $docRenderingContext.getParserId()
getRelativePath() = .
I would expect at least $alignedFileName to return the value another-page.html.
This issue (https://issues.apache.org/jira/browse/MSITE-842) has been solved with a PR provided by the OP.
This was a bug in the maven-site-plugin Maven plugin (the one that runs when you execute "mvn site").
It has been fixed in version 3.8 of the plugin (which hasn't been released yet, at the time of writing).
I have a jmeter test that is already defined in the gui like this.
I am automating running this jmeter test from java, and I want to set ${__P(threads)} from within the java code.
The relevant code is :
public List<String> runJmxTest(String jmxFile, String jtlFile) throws IOException {
HashTree testPlanTree;
List<String> resultSet = new ArrayList<>();
// Initialize JMeter SaveService
SaveService.loadProperties();
JMeterVariables j = new JMeterVariables();
j.put("threads", "10");
// Load existing .jmx Test Plan
File in = new File(jmeterHome.getPath() + "/bin/testPlans/" + jmxFile);
try{
testPlanTree = SaveService.loadTree(in);
} catch (FileNotFoundException e){
resultSet.add("fail");
resultSet.add(e.toString());
return resultSet;
}
// set up custom result collector with summariser
Summariser summer = new Summariser("caos-mbm summariser");
collector = new myResultCollector(summer);
if(jtlFile != null){
if(!jtlFile.contains(".jtl")) {
String jtlTmp = jtlFile.concat(".jtl");
collector.setFilename(jmeterHome.getPath() + "/bin/testPlans/Output/" + jtlTmp);
} else {
collector.setFilename(jmeterHome.getPath() + "/bin/testPlans/Output/" + jtlFile);
}
}
testPlanTree.add(testPlanTree.getArray()[0], collector);
// Run Test Plan
jm.configure(testPlanTree);
jm.run();
resultSet.add("success");
resultSet.add(Double.toString(collector.getErrorPercent()));
return resultSet;
}
I have tried setting the property through the props, adding it to the test plan tree, adding jmeterproperties to the jmetercontext. I can't get it to pick up the variable though.
Any advice would be appreciated. I have also looked through quite a few posts on here that seem similar but the solutions didn't work for me or the implementation was off.
You're using the wrong class, remove these lines:
JMeterVariables j = new JMeterVariables();
j.put("threads", "10");
and add the following instead:
org.apache.jmeter.util.JMeterUtils.setProperty("threads", "10");
You need to do this after loading the Test Plan and before running the test.
Also make sure to add ApacheJMeter_functions.jar to your project CLASSPATH
More information on running JMeter test using JMeter API: Five Ways To Launch a JMeter Test without Using the JMeter GUI
error :_ jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval org/json/simple/JSONArray
Import java method from project jar file which is placed in lib folder.
source code on written for pass json value in arraylist:
import jsonresponse.common.JsonResponseProcessor;
import assertions.AssertResponse;
import databaseresponse.common.DbResponseProcessors;
import org.json.simple.JSONArray;
String resJson = prev.getResponseDataAsString();
String res = resJson.get("queueId");
log.info("----->>>>"+resJson);
ArrayList list1 = new ArrayList();
list1.add("queueId");
list1.add("name");
list1.add("faxNumber");
list1.add("description");
list1.add("type");
ArrayList list2 = new ArrayList();
list2.add("userId");
ArrayList list3 = new ArrayList();
list3.add("agencyId");
ArrayList list4 = new ArrayList();
list4.add("usertypeId");
JsonResponseProcessor obj = new JsonResponseProcessor();
System.out.println("%%%%%%%%%%%%%%fgfggfffgf%%%%%%%%%%%%%%%");
ArrayList Jsoin = obj.getvalueofsubmapoflist(resJson,".result[0]",list1);
System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" +Jsoin);
log.info(">>>"+Jsoin);
Make sure you have all referenced .jar files in JMeter classpath (i.e. copy them to JMeter's "lib" folder). Don't forget to restart JMeter to pick the jars up
If you still experience issues try putting your code inside try block like:
try {
//your code here
}
catch (Throwable ex) {
log.error("Problem in Beanshell", ex);
throw ex;
}
This way you'll have informative stacktrace printed to jmeter.log file.
One more way to get more information regarding your Beanshell script is putting debug(); directive to the beginning of your code. If will trigger debugging output into stdout
See How to Use BeanShell: JMeter's Favorite Built-in Component article for more information on using Java and JMeter APIs from Beanshell test elements in JMeter tests.
I'm looking into providing a 'hot-swap' capability for switching between different versions of sets of drools rules. The target deployment is in WebSphere, and the rules will all be run in stateless session beans. Ideally I want to pre-compile and package the rules into some discrete file and get the Application Server to determine that new rules are available, and load them (skipping the compilation step).
The Drools documentation indicates this should be possible - but is splendidly vague on the mechanics. The details on the Java EE side are not an issue but the pre-compilation is providing an headache.
Following some posts I've pulled together some logic which I thought would do the trick - the following compiles a rules file and serializes it out to disk:
private void process(String outputFile, String inputFile) throws Exception {
String drl = fileToString(inputFile);
KieServices ks = KieServices.Factory.get();
KieFileSystem kfs = ks.newKieFileSystem().write( "src/main/resources/r1.drl", drl );
ks.newKieBuilder( kfs ).buildAll();
ReleaseId releaseId = ks.getRepository().getDefaultReleaseId();
InternalKieModule kieModule = (InternalKieModule) ks.getRepository().getKieModule( releaseId );
byte[] jar = kieModule.getBytes();
serialize(jar, outputFile);
System.out.println("Class of InternalKieModule is " + kieModule.getClass());
}
The following reads it back ready to create a KieSession:
private KieContainer getKbase(KieServices ks) throws Exception {
byte[] jar = deserialize(RULES_SER);
Resource jarRes = ks.getResources().newByteArrayResource(jar);
KieModule km = ks.getRepository().addKieModule(jarRes);
releaseId = km.getReleaseId();
KieContainer kc = ks.newKieContainer(km.getReleaseId());
return kc;
}
Works fine BUT ... I was horrified to discover I seem to need everything but the kitchen sink to actually run it - just under 50 separate jar files - taking up 16 MB and including the Ant jar, 10 Maven jars, and the drools compiler jar even though I'm not supposed to be compiling anything, and I'm certainly not trying to use Maven or Ant! Of the 67 Jar files in the distribution nearly all seem directly linked to Maven, and very few (I'd judge from the approach below about 10 to 15) actually have anything to do with a rules runtime.
Going back to an example I built with Drools 5, several years back, I came up with the following code to reload a drl file I'd compiled separately using the Knowledge Base APIs:
private KnowledgeBase readSavedKnowledgeBase() throws Exception {
byte[] serializedKb = (byte[]) deserialize(RULES_SER);
ByteArrayInputStream bais = new ByteArrayInputStream(serializedKb);
DroolsObjectInputStream ois = new DroolsObjectInputStream(bais);
KnowledgeBase kbase = (KnowledgeBase) ois.readObject();
ois.close();
return kbase;
}
This works fine with 6.1. I only need 9 jars, (and I don't need the compiler jar) - and my run-time is a fairly reasonable 5MB. The down side is that Eclipse is unhappy since the KnowledgeBase class is now deprecated.
Could someone point the way to allowing me to get the same result using non-deprecated classes but without all the baggage of Maven and so on which I don't want or need to actually run some rules?
Some 6.x code for building:
KieServices ks = KieServices.Factory.get();
KieFileSystem kfs = ks.newKieFileSystem();
FileInputStream fis = new FileInputStream( "sale/sale.drl" );
kfs.write( "src/main/resources/sale.drl",
ks.getResources().newInputStreamResource( fis ) );
KieBuilder kieBuilder = ks.newKieBuilder( kfs ).buildAll();
Results results = kieBuilder.getResults();
if( results.hasMessages( Message.Level.ERROR ) ){
System.out.println( results.getMessages() );
throw new IllegalStateException( "### errors ###" );
}
KieContainer kieContainer =
ks.newKieContainer( ks.getRepository().getDefaultReleaseId() );
// CEP - get the KIE related configuration container and set the EventProcessing (from default cloud) to Stream
KieBaseConfiguration config = ks.newKieBaseConfiguration();
config.setOption( EventProcessingOption.STREAM );
KieBase kieBase = kieContainer.newKieBase( config );
// KieSession kieSession = kieContainer.newKieSession();
KieSession kieSession = kieBase.newKieSession();
You can serialize out the KieBase and back in for fast startup. I run this for various tests using the below CLASSPATH, but for execution you'll not need antlr, decisiontables, templates, and (maybe) others.
export CLASSPATH=".:$root/drools-core-${tag}.jar:$root/kie-api-${tag}.jar:$roo/kie-internal-${tag}.jar:$root/knowledge-internal-api-${tag}.jar:$root/drools-compiler-${tag}.jar:$root/antlr-runtime-3.5.jar:$root/ecj-4.3.1.jar:$root/mvel2-2.1.9.Final.jar:$root/drools-decisiontables-${tag}.jar:$root/drools-templates-${tag}.jar:$root/protobuf-java-2.5.0.jar:$root/slf4j-api-1.7.2.jar:$root/xstream-1.4.7.jar:$SLF4J"
For serialiazation and its counterpart use the usual mantra:
ObjectOutputStream out =
new ObjectOutputStream( new FileOutputStream( pkgPath ) );
out.writeObject( kieBase );
out.close();
//---------- In another program ---------------
ObjectInputStream in =
new ObjectInputStream( new FileInputStream( pkgPath ) );
#SuppressWarnings( "unchecked" )
KieBase kieBase = (KieBase)in.readObject();
in.close();
It only brings in Maven if you have kie-ci on the classpath, remove that and you will not have any maven. However you will also not have any dependency management or pom analysis - if you don't need those things, you don't need maven to compile. Without kie-ci it will fall back to a "light" pom.xml parser. You can still programmatically provide it the other kiemodulies it depends on.
I need to generate BPEL XML code in runtime. The only way I can do it now is to create XML document with "bare hands" using DOM API. But there must be a framework that could ease such work incorporating some kind of object model.
I guess it should look something like this:
BPELProcessFactory.CreateProcess().addSequence
Do you know any?
The Eclipse BPEL designer project provides an EMF model for BPEL 2.0. The generated code can be used to programmatically create BPEL code with a convenient API.
In case anyone stumbles upon this.
Yes this can be done using the BPEL Model.
Here is a sample piece of code which generates a quite trivial BPEL file:
public Process createBPEL()
{
Process process = null;
BPELFactory factory = BPELFactory.eINSTANCE;
try
{
ResourceSet rSet = new ResourceSetImpl();
rSet.getResourceFactoryRegistry().getExtensionToFactoryMap()
.put("bpel", new BPELResourceFactoryImpl());
File file = new File("myfile.bpel");
file.createNewFile();
String filePath = file.getAbsolutePath();
System.out.println(filePath);
AdapterRegistry.INSTANCE.registerAdapterFactory( BPELPackage.eINSTANCE, BasicBPELAdapterFactory.INSTANCE );
Resource resource = rSet.createResource(URI.createFileURI(filePath));
process = factory.createProcess();
process.setName("FirstBPEL");
Sequence seq = factory.createSequence();
seq.setName("MainSequence");
Receive recieve = factory.createReceive();
PortType portType = new PortTypeProxy(URI.createURI("http://baseuri"), new QName("qname"));
Operation operation = new OperationProxy(URI.createURI("http://localhost"), portType , "operation_name");
recieve.setOperation(operation);
Invoke invoke = factory.createInvoke();
invoke.setOperation(operation);
While whiles = factory.createWhile();
If if_st = factory.createIf();
List<Activity> activs = new ArrayList<Activity>();
activs.add(recieve);
activs.add(invoke);
activs.add(if_st);
activs.add(whiles);
seq.getActivities().addAll(activs);
process.setActivity(seq);
resource.getContents().add(process);
Map<String,String> map = new HashMap<String, String>();
map.put("bpel", "http://docs.oasis-open.org/wsbpel/2.0/process/executable");
map.put("xsd", "http://www.w3.org/2001/XMLSchema");
resource.save(map);
}
catch(Exception e)
{
e.printStackTrace();
}
return process;
}
The dependencies require that you add the following jars to the project's build path from the plugins folder in eclipse installation directory:
org.eclipse.bpel.model_*.jar
org.eclipse.wst.wsdl_*.jar
org.eclipse.emf.common_*.jar
org.eclipse.emf.ecore_*.jar
org.eclipse.emf.ecore.xmi_*.jar
javax.wsdl_*.jar
org.apache.xerces_*.jar
org.eclipse.bpel.common.model_*.jar
org.eclipse.xsd_*.jar
org.eclipse.core.resources_*.jar
org.eclipse.osgi_*.jar
org.eclipse.core.runtime_*.jar
org.eclipse.equinox.common_*.jar
org.eclipse.core.jobs_*.jar
org.eclipse.core.runtime.compatibility_*.jar