std::map<std::string,std::string> conversion of JavaCPP - javacpp

I'm a newbie of JavaCPP, right now I've got a problem.
my TestLibrary.h:
#include <string>
#include <map>
class TestClass {
public:
TestClass() {
property["a"]="b";
}
const std::map<std::string,std::string>& getMap(std::string str) {
if (str == "a"){
return property;
}
}
std::map<std::string,std::string> property;
};
TestLibrary.java
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
#Platform(include="TestLibrary.h")
public class TestLibrary {
public static class TestClass extends Pointer {
static { Loader.load(); }
public TestClass() { allocate(); }
private native void allocate();
public static native #ByRef KeyValueMap getMap(String str);
}
#Name("std::map<std::string,std::string>") public static class
KeyValueMap extends Pointer {
static { Loader.load(); }
public KeyValueMap(Pointer p) { super(p); }
public KeyValueMap() { allocate(); }
private native void allocate();
public native long size();
#Index public native #StdString BytePointer get(#StdString
BytePointer i);
public native KeyValueMap put(#StdString BytePointer i, BytePointer
value);
}
public static void main(String[] args) {
TestClass l = new TestClass();
KeyValueMap m = l.getMap("a");
System.out.println(m);
//System.out.println(m.get("a"));
}
}
when
javac -cp javacpp.jar TestLibrary.java
java -jar javacpp.jar TestLibrary
jniTestLibrary.cpp:2238:30: error: call to non-static member
function without an object argument
rptr = &::TestClass::getMap(ptr0);
~~~~~~~~~~~~~^~~~~~
the code above is modified from the NativeLibrary example. But How to solve the compile problem?
And can I use m.get("a") like that?

I managed to do this by changing...
TestLibrary.h:
#include <string>
#include <map>
class TestClass {
public:
TestClass() {
property["a"]="b";
}
std::map<std::string,std::string>& getMap(std::string str) {
if (str == "a"){
return property;
}
}
std::map<std::string,std::string> property;
};
TestLibrary.java
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
#Platform(include="TestLibrary.h")
public class TestLibrary {
public static class TestClass extends Pointer {
static { Loader.load(); }
public TestClass() { allocate(); }
private native void allocate();
public native #ByRef KeyValueMap getMap(String str);
}
#Name("std::map<std::string,std::string>")
public static class KeyValueMap extends Pointer {
static { Loader.load(); }
public KeyValueMap(Pointer p) { super(p); }
public KeyValueMap() { allocate(); }
private native void allocate();
public native long size();
#Index public native #StdString BytePointer get(#StdString BytePointer i);
public native KeyValueMap put(#StdString BytePointer i, BytePointer value); }
public static void main(String[] args) {
TestClass l = new TestClass();
KeyValueMap m = l.getMap("a");
System.out.println(m.size());
System.out.println(m.get(new BytePointer("a")).getString());
}}

Related

Extent report is not giving proper report on parallel execution

ReporterClass.Java:
package POM_Classes;
import com.aventstack.extentreports.AnalysisStrategy;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
public class ReporterClass {
public static ExtentHtmlReporter html;
public ExtentReports extent;
public ExtentTest test, suiteTest;
public String testCaseName, testNodes, testDescription, category, authors;
public void startResult() {
html = new ExtentHtmlReporter("./reports/result.html");
html.setAppendExisting(true);
extent = new ExtentReports();
extent.attachReporter(html);
}
/*public ExtentTest startTestModule(String testCaseName, String testDescription) {
suiteTest = extent.createTest(testCaseName, testDescription);
return suiteTest;
}*/
public ExtentTest startTestCase(String testName) {
System.out.println(testName);
test = extent.createTest(testName);
return test;
}
public void reportStep(String desc, String status) {
if (status.equalsIgnoreCase("PASS")) {
test.pass(desc);
} else if (status.equalsIgnoreCase("FAIL")) {
test.fail(desc);
} else if (status.equalsIgnoreCase("WARNING")) {
test.warning(desc);
} else if (status.equalsIgnoreCase("INFO")) {
test.info(desc);
}
}
public void endTestcase() {
extent.setAnalysisStrategy(AnalysisStrategy.CLASS);
}
public void endResult() {
extent.flush();
}
}
Usage:
#Test
public void 961_NavigateToMyAlertsAndAddNewAlerts()
throws IOException, InterruptedException, ATUTestRecorderException, APIException {
driver = launchTargetUrl(this.getClass().getSimpleName().toString());
startResult();
test = startTestCase(Thread.currentThread().getStackTrace()[1].getMethodName().toString());
LoginApplication(driver,transactionusername, transactionuserpassword,test);
HomePage homePage = new HomePage(driver,test);
homePage.MyAlerts.click();
MyAlerts myalerts = new MyAlerts(driver,test);
String selectedcardName;
selectedcardName = driver.findElement(myalerts.cardName).getText().trim();
System.out.println(selectedcardName);
}
#AfterMethod
public void afterMethod(ITestResult result) throws ATUTestRecorderException {
resultOfTest(result);
endTestcase();
endResult();
closeBrowsers(driver);
}
The test case which first gets completed has the report and if the another test case is completed then that result overrides the old one..
If I change public static ExtentReports extent; then it maintains only thread so it logs only one test case and the other parallel execution is not even recorded.. How to resolve this?
Ok, here you go. I haven't tested this yet, but this should allow you to use Extent with parallel usage.
Reporter:
public abstract class ReporterClass {
private static final ExtentReports EXTENT = ExtentManager.getInstance();
public ExtentTest test, suiteTest;
public String testCaseName, testNodes, testDescription, category, authors;
public synchronized ExtentTest startTestCase(String testName) {
System.out.println(testName);
return ExtentTestManager.createTest(testName);
}
public synchronized void reportStep(String desc, String status) {
if (status.equalsIgnoreCase("PASS")) {
ExtentTestManager.getTest().pass(desc);
} else if (status.equalsIgnoreCase("FAIL")) {
ExtentTestManager.getTest().fail(desc);
} else if (status.equalsIgnoreCase("WARNING")) {
ExtentTestManager.getTest().warning(desc);
} else if (status.equalsIgnoreCase("INFO")) {
ExtentTestManager.getTest().info(desc);
}
}
public synchronized void endResult() {
EXTENT.flush();
}
#BeforeMethod
public synchronized void beforeMethod(Method method) {
startTestCase(method.getName());
}
#AfterMethod
public synchronized void afterMethod(ITestResult result) throws ATUTestRecorderException {
reportStep(result.getThrowable(), result.getStatus());
endResult();
closeBrowsers(driver);
}
}
Base:
public abstract class BaseClass extends ReporterClass {
// .. abstractions
}
Extent utils:
public class ExtentTestManager {
static Map<Integer, ExtentTest> extentTestMap = new HashMap<Integer, ExtentTest>();
private static final ExtentReports EXTENT = ExtentManager.getInstance();
public static synchronized ExtentTest getTest() {
return extentTestMap.get((int) (long) (Thread.currentThread().getId()));
}
public static synchronized ExtentTest createTest(String testName) {
return createTest(testName, "");
}
public static synchronized ExtentTest createTest(String testName, String desc) {
ExtentTest test = EXTENT.createTest(testName, desc);
extentTestMap.put((int) (long) (Thread.currentThread().getId()), test);
return test;
}
}
public class ExtentManager {
private static ExtentReports extent;
public synchronized static ExtentReports getInstance() {
if (extent == null) {
createInstance("reports/extent.html");
}
return extent;
}
public synchronized static ExtentReports createInstance(String fileName) {
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(fileName);
htmlReporter.config().setTestViewChartLocation(ChartLocation.BOTTOM);
htmlReporter.config().setChartVisibilityOnOpen(true);
htmlReporter.config().setTheme(Theme.STANDARD);
htmlReporter.config().setDocumentTitle(fileName);
htmlReporter.config().setEncoding("utf-8");
htmlReporter.config().setReportName(fileName);
htmlReporter.setAppendExisting(true);
extent = new ExtentReports();
extent.setAnalysisStrategy(AnalysisStrategy.CLASS);
extent.attachReporter(htmlReporter);
return extent;
}
}
Finally, your slim tests. Notice there is 0 lines of reporter code here - see ReporterClass.
public class MyTestsClass extends BaseClass {
#Test
public void 961_NavigateToMyAlertsAndAddNewAlerts()
throws IOException, InterruptedException, ATUTestRecorderException, APIException {
driver = launchTargetUrl(this.getClass().getSimpleName().toString());
LoginApplication(driver,transactionusername, transactionuserpassword,test);
HomePage homePage = new HomePage(driver,test);
homePage.MyAlerts.click();
MyAlerts myalerts = new MyAlerts(driver,test);
String selectedcardName;
selectedcardName = driver.findElement(myalerts.cardName).getText().trim();
System.out.println(selectedcardName);
}
}
//Add below class in your Project. First you need to add the respective object and
//call them respectively. Declaring Extent and Driver as static is a big problem in
//Parallel/execution.
//Avoid using static as far as possible by using the below class.
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.WebDriver;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
public class WebDriverFactory {
private static ThreadLocal<WebDriver> drivers=new ThreadLocal<>();
private static List<WebDriver> storeDrivers=new ArrayList<WebDriver>();
private static List<ExtentTest> extent=new ArrayList<ExtentTest>();
private static ThreadLocal<ExtentTest> reports=new ThreadLocal<ExtentTest>();
static
{
Runtime.getRuntime().addShutdownHook(new Thread(){
public void run()
{
storeDrivers.stream().forEach(WebDriver::quit);
}
});
}
public static WebDriver getDriver()
{
return drivers.get();
}
public static ExtentTest getextentReportObject()
{
return reports.get();
}
public static void addDriver(WebDriver driver)
{
storeDrivers.add(driver);
drivers.set(driver);
}
public static void addExtentReportObject(ExtentTest report)
{
extent.add(report);
reports.set(report);
}
public static void removeDriver()
{
storeDrivers.remove(drivers.get());
drivers.remove();
}
}
//Add and Invoke the object in the following way
/*** Add and invoke the object in the below fashion **/
WebDriverFactory.addExtentReportObject(extent.createTest("Monitor Scenario
").createNode("Monitor Page Validation"));
WebDriverFactory.getextentReportObject().assignCategory("#SmokeTest");

About Singleton class

package com.java2novice.algos;
public class MySingletonExample {
private static MySingletonExample myObjct;
static{
myObjct = new MySingletonExample();
}
private MySingletonExample(){
}
public static MySingletonExample getInstance(){
return myObjct;
}
public void runMe(){
System.out.println("Hey, it is working!!!");
}
public static void main(String [] args){
MySingletonExample mse = getInstance();
ms.runMe();
}
}
Can anyone please give a description of the above program why static is used here and why provide a static method to get instance of the object ?

React 0.18 causes Module error

I'm getting the following error when trying to get a Module working after updating to React Native 0.18:
com.lwansbrough.RCTCamera.RCTCameraViewManager cannot be cast to
com.facebook.react.uimanager.ViewGroupmanager
What causes this type of error, and how can it be resolved?
Here is the code for RCTCameraViewManager:
package com.lwansbrough.RCTCamera;
import android.support.annotation.Nullable;
import com.facebook.react.uimanager.*;
public class RCTCameraViewManager extends SimpleViewManager<RCTCameraView> {
private static final String REACT_CLASS = "RCTCameraView";
#Override
public String getName() {
return REACT_CLASS;
}
#Override
public RCTCameraView createViewInstance(ThemedReactContext context) {
return new RCTCameraView(context);
}
#ReactProp(name = "aspect")
public void setAspect(RCTCameraView view, int aspect) {
view.setAspect(aspect);
}
#ReactProp(name = "captureMode")
public void setCaptureMode(RCTCameraView view, int captureMode) {
// TODO - implement video mode
}
#ReactProp(name = "captureTarget")
public void setCaptureTarget(RCTCameraView view, int captureTarget) {
// No reason to handle this props value here since it's passed again to the RCTCameraModule capture method
}
#ReactProp(name = "type")
public void setType(RCTCameraView view, int type) {
view.setCameraType(type);
}
#ReactProp(name = "torchMode")
public void setTorchMode(RCTCameraView view, int torchMode) {
view.setTorchMode(torchMode);
}
#ReactProp(name = "flashMode")
public void setFlashMode(RCTCameraView view, int flashMode) {
view.setFlashMode(flashMode);
}
#ReactProp(name = "orientation")
public void setOrientation(RCTCameraView view, int orientation) {
view.setOrientation(orientation);
}
#ReactProp(name = "captureAudio")
public void setCaptureAudio(RCTCameraView view, boolean captureAudio) {
// TODO - implement video mode
}
}
I also got this error, my solution was to change the
public class RCTCameraViewManager extends SimpleViewManager<RCTCameraView>
to
public class RCTCameraViewManager extends ViewGroupManager<RCTCameraView>

JNA complex union structure mapping

In JNA,how to map a complex union structure from follows c codes:
typedef struct {
char *vmxSpec;
char *serverName;
char *thumbPrint;
long privateUse;
VixDiskLibCredType credType;//enum type
union VixDiskLibCreds {
struct VixDiskLibUidPasswdCreds {
char *userName;
char *password;
} uid;
struct VixDiskLibSessionIdCreds {
char *cookie;
char *userName;
char *key;
} sessionId;
struct VixDiskLibTicketIdCreds *ticketId;
} creds;
uint32 port;
} VixDiskLibConnectParams;
when i mapping the struct,it throws a NullPointerException:
Exception in thread "Thread-56" java.lang.NullPointerException
at java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:290)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:157)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:146)
at java.util.Arrays.sort(Arrays.java:472)
at java.util.Collections.sort(Collections.java:155)
at com.sun.jna.Structure.sort(Structure.java:889)
at com.sun.jna.Structure.getFields(Structure.java:921)
at com.sun.jna.Structure.deriveLayout(Structure.java:1054)
at com.sun.jna.Structure.calculateSize(Structure.java:978)
at com.sun.jna.Structure.calculateSize(Structure.java:945)
at com.sun.jna.Structure.allocateMemory(Structure.java:375)
at com.sun.jna.Structure.<init>(Structure.java:184)
at com.sun.jna.Structure.<init>(Structure.java:172)
at com.sun.jna.Structure.<init>(Structure.java:159)
at com.sun.jna.Structure.<init>(Structure.java:151)
at com.test.vmm.vdp.VixDiskLibrary$VixDiskLibConnectParams.<init>(VixDiskLibrary.java:71)
at com.test.vmm.vdp.VixDiskLibrary$VixDiskLibConnectParams$ByReference.<init>(VixDiskLibrary.java:72)
at com.test.vmm.vdp.VixDiskLib.run(VixDiskLib.java:47)
at java.lang.Thread.run(Thread.java:744)
my code as follows:
public static class VixDiskLibConnectParams extends Structure {
public static class ByReference extends VixDiskLibConnectParams implements Structure.ByReference {}
public static class ByValue extends VixDiskLibConnectParams implements Structure.ByValue {}
public static class VixDiskLibCreds extends Union {
public static class ByReference extends VixDiskLibCreds implements Structure.ByReference {}
public static class ByValue extends VixDiskLibCreds implements Structure.ByValue {}
public VixDiskLibUidPasswdCreds uid;
public VixDiskLibSessionIdCreds sessionId;
public VixDiskLibTicketIdCreds.ByReference ticketId;
public static class VixDiskLibUidPasswdCreds extends Structure {
public static class ByReference extends VixDiskLibUidPasswdCreds implements Structure.ByReference {}
public String userName;
public String password;
protected List getFieldOrder() {
List list = new ArrayList();
list.add(userName);
list.add(password);
return list;
}
}
public static class VixDiskLibSessionIdCreds extends Structure {
public static class ByReference extends VixDiskLibSessionIdCreds implements Structure.ByReference {}
public String cookie;
public String userName;
public String key;
protected List getFieldOrder() {
List list = new ArrayList();
list.add(cookie);
list.add(userName);
list.add(key);
return list;
}
}
public static class VixDiskLibTicketIdCreds extends Structure {
public static class ByReference extends VixDiskLibUidPasswdCreds implements Structure.ByReference {}
protected List getFieldOrder() {
List list = new ArrayList();
return list;
}
}
protected List getFieldOrder() {
List list = new ArrayList();
list.add(uid);
list.add(sessionId);
list.add(ticketId);
return list;
}
}
public String vmxSpec;
public String serverName;
public String thumbPrint;
public NativeLong privateUse;
public int credType;
public VixDiskLibCreds.ByValue creds;
public int port;
public void read() {
super.read();
switch (credType) {
case VixDiskLibCredType.VIXDISKLIB_CRED_UID:
creds.setType(VixDiskLibCreds.VixDiskLibUidPasswdCreds.class);
creds.read();
break;
case VixDiskLibCredType.VIXDISKLIB_CRED_SESSIONID:
creds.setType(VixDiskLibCreds.VixDiskLibSessionIdCreds.class);
creds.read();
break;
case VixDiskLibCredType.VIXDISKLIB_CRED_TICKETID:
creds.setType(VixDiskLibCreds.VixDiskLibTicketIdCreds.class);
creds.read();
break;
case VixDiskLibCredType.VIXDISKLIB_CRED_SSPI:
System.out.println("VixDiskLibCredType : VIXDISKLIB_CRED_SSPI");
break;
default:
System.out.println("VixDiskLibCredType : unknow");
break;
}
}
protected List getFieldOrder() {
List list = new ArrayList();
list.add(vmxSpec);
list.add(serverName);
list.add(thumbPrint);
list.add(privateUse);
list.add(credType);
list.add(creds);
list.add(port);
return list;
}
}
what's wrong?A clear explanation on how to do it will be better.
Thanks
i have found the problem, quotes are forgotten in the method add() when called to add element by List
The correct code will be:
protected List getFieldOrder() {
List list = new ArrayList();
list.add("userName");
list.add("password");
return list;
}

Ninject issue with contextual binding and Lazy<T>

Ninject doesn't seem to correctly use WhenInjectedInto contstraint while also using Lazy<T>. Check the following example. The OnLandAttack and the OnLandAttackLazy should each be using the Samurai instance. But the Lazy<T> version ends up with the SpecialNinja instance. I'm guessing it's because it's not actually initialized in the contructor? But the type should still be correctly registered I would think. Am I missing something? FYI, this is using Ninject 3.2.2 and the Ninject.Extensions.Factory extension 3.2.1
class Program
{
static void Main(string[] args)
{
var kernel = new StandardKernel();
kernel.Load(new WarriorModule());
var amphibious = kernel.Get<IAttack>("amphibious");
amphibious.Execute();
var onLand = kernel.Get<IAttack>("onLand");
onLand.Execute();
var onLandLazy = kernel.Get<IAttack>("onLandLazy");
onLandLazy.Execute();
Console.ReadKey();
}
}
public class WarriorModule : NinjectModule
{
public override void Load()
{
Bind<IWarrior>().To<Samurai>().WhenInjectedInto<OnLandAttack>();
Bind<IWarrior>().To<Samurai>().WhenInjectedInto<OnLandAttackLazy>();
Bind<IWarrior>().To<SpecialNinja>(); // <-- for everything else
Bind<IAttack>().To<AmphibiousAttack>().Named("amphibious");
Bind<IAttack>().To<OnLandAttack>().Named("onLand");
Bind<IAttack>().To<OnLandAttackLazy>().Named("onLandLazy");
}
}
public interface IWarrior
{
void Attack();
}
public class Samurai : IWarrior
{
public void Attack()
{
Console.WriteLine("\tSamurai Attack");
}
}
public class SpecialNinja : IWarrior
{
public void Attack()
{
Console.WriteLine("\tSpecial Ninja Attack");
}
}
public interface IAttack
{
void Execute();
}
public class OnLandAttack : IAttack
{
private readonly IWarrior warrior;
public OnLandAttack(IWarrior warrior)
{
this.warrior = warrior;
}
public void Execute()
{
Console.WriteLine("Begin OnLand attack");
this.warrior.Attack();
}
}
public class OnLandAttackLazy : IAttack
{
private readonly Lazy<IWarrior> warrior;
public OnLandAttackLazy(Lazy<IWarrior> warrior)
{
this.warrior = warrior;
}
public void Execute()
{
Console.WriteLine("Begin OnLandLazy attack");
this.warrior.Value.Attack();
}
}
public class AmphibiousAttack : IAttack
{
private readonly IWarrior warrior;
public AmphibiousAttack(IWarrior warrior)
{
this.warrior = warrior;
}
public void Execute()
{
Console.WriteLine("Begin Amphibious attack");
this.warrior.Attack();
}
}