Read test data from Mercury Quality center 9 via java - java

We use Mercury Quality Center 9 for storage tests and test results.
I need to read test data from Test Plan and to write test result into Test Lab via java.
I tried to find about this in google but I have not found anything.
UPDATE:
I tried to use qctools4j for working with MQC 9 with the following code:
public void connect() {
try{
IQcConnection conn = QcConnectionFactory.createConnection("http://qc/qcbin");
conn.connect("login", "password", "DEFAULT","project");
TestClient tc = conn.getTestClient();
System.out.println("Connection success!!!");
}
catch (QcException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
I got the following exception message:
*org.qctools4j.exception.QcException: Can't co-create object
at org.qctools4j.clients.QcConnectionImpl.initConnection(Unknown Source)
at org.qctools4j.clients.QcConnectionImpl.<init>(Unknown Source)
at org.qctools4j.QcConnectionFactory.createConnection(Unknown Source)
at automation_framework1.automation_framework1.QCWorker.connect1(QCWorker.java:38)
at automation_framework1.automation_framework1.Main.main(Main.java:12)
Caused by: com.jacob.com.ComFailException: Can't co-create object
at com.jacob.com.Dispatch.createInstanceNative(Native Method)
at com.jacob.com.Dispatch.<init>(Dispatch.java:99)
at com.jacob.activeX.ActiveXComponent.<init>(ActiveXComponent.java:58)
at org.qctools4j.clients.QcConnectionImpl.initConnection(Unknown Source)*
What am I doing wrong?

I took part in developping QC 9 and I am not sure there is Java API. However, there is a COM interface or OTA API. You can use some library that helps to call COM API from Java.
For example:
Jacob it is open source and here are some examples.
Nevaobject - it is commercial but more stable.
Good luck!
EDIT:
just saw qctools4j (it is based on Jacob) - never tried it.

I found how to solve the problem. I used groovy scriptom with the following code (may be it will help somebody):
def tdc;
public QualityCenterController(){
static{
System.load("C:\\WINDOWS\\system32\\OTAClient.dll");
System.load("D:\\Work\\automation_framework\\libs\\lib\\jacob-1.16-M2-x86.dll");
}
public void connect(){
tdc = new ActiveXObject ("TDApiOle80.TDConnection");
tdc.InitConnectionEx("http://qc/qcbin");
tdc.Login("username", "password");
tdc.Connect("DEFAULT","PROJECT");
System.out.println("login is success");
}
//ReqFactory Object
public void getRequirements(){
def requironmetns = tdc.ReqFactory();
def listReq = requironmetns.NewList("");
for (def iterReq : listReq) {
getRequirement(iterReq);
}
println listReq.count();
}
//Req Object
public void getRequirement(def itemReq){
println 'ID: '+itemReq.ID();
println 'Name:' + itemReq.Name();
println 'Path:' + itemReq.Path();
println 'Reviewed:' + itemReq.Reviewed();
println 'Author:' + itemReq.Author();
println 'Priority: ' + itemReq.Priority();
println 'Comment: '+removeHtmlTag(itemReq.Comment());
println 'Type: ' + itemReq.Type();
}
public Test getTestsFromTestLab(String path){
Test resultTest = new Test();
def labFolder = tdc.TestSetTreeManager.NodeByPath(path);
def tsList = labFolder.FindTestInstances("");
for (def iterable_element : tsList){
Test test = getTestData(iterable_element);
def steps = iterable_element.Test().DesignStepFactory();
TestStep testStep = getTest(steps);
}
return resultTest;
}
public TestStep getTest(def testData){
TestStep testStep = new TestStep();
def listSteps = testData.NewList("");
for(def item1 : listSteps){
testStep = getTestStepData(item1);
showTestStep(testStep);
}
return testStep;
}
private TestStep getTestStepData(def stepData){
TestStep testStep = new TestStep();
testStep.setId(stepData.ID());
testStep.setName(stepData.StepName());
testStep.setDescription(removeHtmlTag(stepData.StepDescription()));
testStep.setExpected(removeHtmlTag(stepData.StepExpectedResult()));
testStep.setStepOrder(stepData.Order());
return testStep;
}
public Test getTestData(def testData){
Test test = new Test();
test.setId(Integer.parseInt(testData.Id()));
test.setName(testData.Name());
test.setExecStatus(testData.Status());
showTest(test);
return test;
}
private String removeHtmlTag(String html){
String result = "";
result = Jsoup.parse(html).text();
return result;
}
public void showTestStep(TestStep testStep){
println testStep.getId();
println testStep.getName();
println testStep.getDescription();
println testStep.getExpected();
println testStep.getStepOrder();
}
public void showTest(Test test){
println test.getId();
println test.getName();
println test.getExecStatus();
}

Related

PlantUML graph generation in java Illegal acces error

I'm trying to make a simple graph using java but keep getting error
Code:
public class PlantUMLDemoMain {
public static void main(String[] args) throws Exception {
generateFromStringSource(new File("from-string.png"));
generateFromApi(new File("from-api.png"));
}
private static void generateFromApi(File file) throws IOException {
// 1. setup:
SequenceDiagramFactory f = new SequenceDiagramFactory();
SequenceDiagram diagram = f.createEmptyDiagram();
// 2. Build the diagram:
// "Bob -> Alice : hello"
// See net.sourceforge.plantuml.sequencediagram.command.CommandArrow#executeArg
Display bobD = Display.getWithNewlines("Bob");
Participant bobP = diagram.getOrCreateParticipant("Bob", bobD);
Display aliceD = Display.getWithNewlines("Alice");
Participant aliceP = diagram.getOrCreateParticipant("Alice", aliceD);
Display label = Display.getWithNewlines("hello");
ArrowConfiguration config = ArrowConfiguration.withDirectionNormal();
Message msg = new Message(bobP, aliceP, label, config, diagram.getNextMessageNumber());
checkState(null == diagram.addMessage(msg));
// 3. Output the diagram
// See net.sourceforge.plantuml.SourceStringReader#generateImage
diagram.makeDiagramReady();
checkState(1 == diagram.getNbImages());
try (OutputStream os = new FileOutputStream(file)) {
ImageData imageData = diagram.exportDiagram(os, 0, new FileFormatOption(FileFormat.PNG));
System.out.println("generateFromApi: " + diagram.getDescription().getDescription());
}
}
private static void generateFromStringSource(File file) throws IOException {
String source = "#startuml\n";
source += "Bob -> Alice : hello\n";
source += "#enduml\n";
StringBuffer stringBuffer = new StringBuffer();
SourceStringReader reader = new SourceStringReader(source);
// Write the first image to "png"
String desc = reader.generateImage(file);
// Return a null string if no generation
System.out.println("generateFromStringSource: " + desc);
}
}
Error: Exception in thread "main" java.lang.IllegalAccessError: class net.sourceforge.plantuml.png.PngIOMetadata (in unnamed module #0x9597028) cannot access class com.sun.imageio.plugins.png.PNGMetadata (in module java.desktop) because module java.desktop does not export com.sun.imageio.plugins.png to unnamed module #0x9597028
at net.sourceforge.plantuml.png.PngIOMetadata.writeWithMetadata(PngIOMetadata.java:60)
at net.sourceforge.plantuml.png.PngIO.write(PngIO.java:86)
at net.sourceforge.plantuml.png.PngIO.write(PngIO.java:80)
at net.sourceforge.plantuml.ugraphic.g2d.UGraphicG2d.writeImageTOBEMOVED(UGraphicG2d.java:219)
at net.sourceforge.plantuml.ugraphic.ImageBuilder.writeImageInternal(ImageBuilder.java:249)
at net.sourceforge.plantuml.ugraphic.ImageBuilder.writeImageTOBEMOVED(ImageBuilder.java:171)
at net.sourceforge.plantuml.sequencediagram.graphic.SequenceDiagramFileMakerPuma2.createOne(SequenceDiagramFileMakerPuma2.java:234)
at net.sourceforge.plantuml.sequencediagram.SequenceDiagram.exportDiagramInternal(SequenceDiagram.java:222)
at net.sourceforge.plantuml.UmlDiagram.exportDiagramNow(UmlDiagram.java:236)
at net.sourceforge.plantuml.AbstractPSystem.exportDiagram(AbstractPSystem.java:127)
at net.sourceforge.plantuml.SourceStringReader.generateImage(SourceStringReader.java:124)
at net.sourceforge.plantuml.SourceStringReader.generateImage(SourceStringReader.java:111)
at net.sourceforge.plantuml.SourceStringReader.generateImage(SourceStringReader.java:101)
at scr.graphviz.sk.PlantUMLDemoMain.generateFromStringSource(PlantUMLDemoMain.java:66)
at scr.graphviz.sk.PlantUMLDemoMain.main(PlantUMLDemoMain.java:23)
I found someone with similar problem and older version of plantuml worked for him. I have jar file of the older version but I'm not sure how to apply it. I tried inspecting the file and find out versions of libraries used and added maven dependencies for them but it didnt seem to work.
This is similar problem i mentioned https://github.com/plantuml/plantuml/issues/69

Problem while authenticating URL in spock testing

I have a groovy file gitClone.groovy which has a function call.
def call(credentials, url, project, branch, path, refs, noTags=false,
timeout=20)
{
}
I am writing a test for validating the 'url'. I want to write a test case which will validate if the url is correct or not. My test file is as follows:
gitCloneSpec.groovy
import com.homeaway.devtools.jenkins.testing.JenkinsPipelineSpecification;
import spock.lang.*
import java.net.URL;
public class gitCloneSpec extends JenkinsPipelineSpecification {
def gitClone = null
def check = 0
def setup() {
gitClone = loadPipelineScriptForTest("vars/gitClone.groovy")
gitClone.getBinding().setVariable( "url", "https://www.google.com/")
}
def "validate url"(){
when:
try {
URL u = new URL(url)
u.toURI()
check = 1
}
// If there was an Exception
// while creating URL object
catch (Exception e) {
check = 2;
}
then:
check == 1
}
}
Somehow url is not able to store the string "http://www.google.com" and it is throwing the exception where 'check' is getting updated with value '2'
How can I perform this test?

how to use try-resources in kotlin?

I am trying to use kotlin instead of Java, I cannot find a good way to do with try resource:
Java Code like this:
import org.tensorflow.Graph;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
import org.tensorflow.TensorFlow;
public class HelloTensorFlow {
public static void main(String[] args) throws Exception {
try (Graph g = new Graph()) {
final String value = "Hello from " + TensorFlow.version();
// Construct the computation graph with a single operation, a constant
// named "MyConst" with a value "value".
try (Tensor t = Tensor.create(value.getBytes("UTF-8"))) {
// The Java API doesn't yet include convenience functions for adding operations.
g.opBuilder("Const", "MyConst").setAttr("dtype", t.dataType()).setAttr("value", t).build();
}
// Execute the "MyConst" operation in a Session.
try (Session s = new Session(g);
// Generally, there may be multiple output tensors,
// all of them must be closed to prevent resource leaks.
Tensor output = s.runner().fetch("MyConst").run().get(0)) {
System.out.println(new String(output.bytesValue(), "UTF-8"));
}
}
}
}
I do it in kotlin, I have to do this:
fun main(args: Array<String>) {
val g = Graph();
try {
val value = "Hello from ${TensorFlow.version()}"
val t = Tensor.create(value.toByteArray(Charsets.UTF_8))
try {
g.opBuilder("Const", "MyConst").setAttr("dtype", t.dataType()).setAttr("value", t).build()
} finally {
t.close()
}
var sess = Session(g)
try {
val output = sess.runner().fetch("MyConst").run().get(0)
println(String(output.bytesValue(), Charsets.UTF_8))
} finally {
sess?.close()
}
} finally {
g.close()
}
}
I have try to use use like this:
Graph().use {
it -> ....
}
I got error like this:
Error:(16, 20) Kotlin: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
#InlineOnly public inline fun ???.use(block: (???) -> ???): ??? defined in kotlin.io
I just use wrong dependency:
compile "org.jetbrains.kotlin:kotlin-stdlib"
replace it with:
compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8"

Command Line Output of .jar is Different than its Output When Run by C# Code

I have a .jar file named "DynamicContentLoader.jar" that executes a Java process that connects to a web page, using HtmlUnit, and prints its Html document via System.out.println();. This Process takes one argument from the command line: the URI of the webpage needed to be retrieved.
Code of the Java process thats exported to the .jar file:
import java.io.IOException;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class DynamicContentLoader {
public static void main(String[] args) {
java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(java.util.logging.Level.OFF);
String s = DynamicContentLoader.loadHtml("https://query.nytimes.com/search/sitesearch/?action=click&contentCollection&region=TopBar&WT.nav=searchWidget&module=SearchSubmit&pgtype=Homepage#/Donald%20Trump");
System.out.println(s);
}
public static String loadHtml(String url) {
final WebClient webClient = new WebClient(BrowserVersion.CHROME);
webClient.getOptions().setCssEnabled(false); //if you don't need css
webClient.getOptions().setThrowExceptionOnScriptError(false); // stop process breaking exception throws
HtmlPage page;
try {
page = webClient.getPage(url);
webClient.waitForBackgroundJavaScript(20 * 1000); /* will wait JavaScript to execute up to 5s */
String pageAsXml = page.asXml();
webClient.close();
return pageAsXml;
} catch (FailingHttpStatusCodeException | IOException e) {
return null;
}
}
}
Next, I execute this .jar within a Mono project with a class that uses a Process Object to execute the .jar, read its StandardOutput stream into a StringBuilder, then create and return an HtmlAgilityPack.HtmlDocument object from StringBuilder.ToString();:
using System;
using System.Diagnostics;
using System.Text;
using HtmlAgilityPack;
namespace Search {
public static class DynamicContentLoader {
// path of .jar file in ProjectDirectory/Resources/.jar
readonly static string jarPath =
AppDomain.CurrentDomain.BaseDirectory +
"Resources/DynamicContentLoader.jar";
public static HtmlDocument LoadDynamicWebPage(string url) {
var startInfo = new ProcessStartInfo("java", #" -jar "
+ jarPath + " \'" + url + "\'");
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
var javaProcess = new Process();
javaProcess.StartInfo = startInfo;
javaProcess.Start();
var output = new StringBuilder();
while (!javaProcess.HasExited) {
output.Append(javaProcess.StandardOutput.ReadToEnd());
}
if (output.Length > 0) {
var doc = new HtmlDocument();
doc.LoadHtml(output.ToString());
// looking see if correct Html doc
Console.WriteLine(doc.DocumentNode.InnerHtml);
return doc;
}
return null;
}
}
}
My issue is that when I run the .jar from the command line,
"java -jar path/to/file/DynamicContentLoader.jar 'some uri'"
I get the correctly loaded Html doc/string. However, my C# code above returns a different, incomplete Html doc/string, or even crashes with exceptions like:
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
atsun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
atorg.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
Caused by: com.gargoylesoftware.htmlunit.ScriptException: TypeError:
Cannot find function all in object function Promise() { [native code] }
Does anyone know what may cause the difference in behavior between these two different execution methods or what will fix this issue?

Calling python module from Java

I want to call a function from a python module from Java using "PythonInterpreter" and here's my Java code
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys\nsys.path.append('C:\\Python27\\Lib\\site-packages')\nimport helloworld");
PyObject someFunc = interpreter.get("helloworld.getName");
PyObject result = someFunc.__call__();
String realResult = (String) result.__tojava__(String.class);
System.out.println(realResult);
and the Python code (helloworld.py) is below:
from faker import Factory
fake = Factory.create()
def getName():
name = fake.name()
return name
The problem I'm facing is while I'm calling interpreter.get when it returns a null PyObject.
Any idea what's going wrong? The python code runs fine from IDLE
EDIT
I just did a bit of change in the code as below
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys\nsys.path.append('C:\\Python27\\Lib\\site-packages')\nimport helloworld");
PyInstance wrapper = (PyInstance)interpreter.eval("helloworld" + "(" + ")");
PyObject result = wrapper.invoke("getName()");
String realResult = (String) result.__tojava__(String.class);
System.out.println(realResult);
and I introduced a class in my python module
from faker import Factory
class helloworld:
def init(self):
fake = Factory.create()
def getName():
name = fake.name()
return name
Now am getting the error below
Exception in thread "main" Traceback (innermost last):
File "<string>", line 1, in ?
TypeError: call of non-function (java package 'helloworld')
You cannot use python attribute access in PythonInterpreter.get. Just use attribute name to get the module, and retrieve attribute from it.
(EDIT PART) Python code is totally broken. Please see the proper example below. And, of course, www.python.org.
(EDIT PART) First parameter of PyInstance.invoke should be method name.
Below you can find working code sample for both cases
Main.java
import org.python.core.*;
import org.python.util.PythonInterpreter;
public class Main {
public static void main(String[] args) {
test1();
test2();
}
private static void test1() {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import hello_world1");
PyObject func = interpreter.get("hello_world1").__getattr__("get_name");
System.out.println(func.__call__().__tojava__(String.class));
}
private static void test2() {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("from hello_world2 import HelloWorld");
PyInstance obj = (PyInstance)interpreter.eval("HelloWorld()");
System.out.println(obj.invoke("get_name").__tojava__(String.class));
}
}
hello_world1.py
def get_name():
return "world"
hello_world2.py
class HelloWorld:
def __init__(self):
self.world = "world"
def get_name(self):
return self.world

Categories

Resources