phonegap android plugin using a native library - java

I'm trying to create a phonegap plugin for an android device, sadly my Java is terrible.
I have a simple helloworld project i'm working in to try and get this going.
I've created a plugin which loads fine and works ( just a simple return string example )
From this i then have tried to add my native library code.
public class Medida extends CordovaPlugin
{
static {
System.loadLibrary("finger");
}
public native static int SFM_Init(byte[] dev);
The error message i keep encountering is:
10-28 15:23:03.207: W/dalvikvm(11618): No implementation found for native Lorg/apache/cordova/plugin/Medida;.SFM_Init ([B)I
Now - I'm taking the libfinger.so file from a full JAVA android project and trying to wrap it into a phonegap plugin (why? Because i can code phonegap, but no java).
The files are all been placed in the correct locations
the libfinger.so file is in the libs/ folder
So my question is - what else do i need to add-in or do to get the JAVA plugin to work with the libfinger.so - so i can call all the clases etc..
Thanks for looking - spents days trying to find out, but there is not much info on calling loadlibrary for plugins which i understand.
John
Main java class
package org.apache.cordova.plugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class Medida extends CordovaPlugin{
static {
System.loadLibrary("finger");
}
public native static int SFM_Init(byte[] dev);
static final String LOG_TAG = "Medida.Java: ";
int fd = 0;
String retval = null;
int[] nQuality = {0};
int[] nBufferSize = {0};
private final String retSuccess = "OK";
public static final int REFRESH = 1;
public static final int ERROR = 0;
private Thread thread = null;
private int peripheral_fd = 1;
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("dave")) {
String message = args.getString(0);
this.dave("Medida CALLING DAVE " + message, callbackContext);
return true;
}
else if (action.equals("scanfinger_getID")){
this.scanfinger_getID( args, callbackContext);
return true;
}
return false;
}
private void dave(String message, CallbackContext callbackContext) {
if (message != null && message.length() > 0) {
callbackContext.success(" --- Medida FROM DAVE: " + message);
} else {
callbackContext.error("Expected one non-empty string argument.");
}
}
private void scanfinger_getID(JSONArray args, CallbackContext callbackContext) throws JSONException {
String message = args.getString(0);
JSONObject object = new JSONObject(message);
String id = object.getString("id");
String dev = "/dev/ttySAC3";
byte[] devName = dev.getBytes();
fd = SFM_Init(devName);
callbackContext.success("Got to scanfinger_getID: " + id);
}
}

Try to define the method as a class method (taken from here):
public class Medida extends CordovaPlugin {
static {
System.loadLibrary("finger");
}
public native int SFM_Init(byte[] dev);
}
EDIT
From the error it seems that there is no method called SFM_Init in the native library, try to list the exported methods and see the exact definition: How do I list the symbols in a .so file

Related

JNA: Missing some specifics methods

I'm wanting create a dll injector in Java ( and only in Java ) for educational proporses for myself and found a basic example in a website especialized in online game.
The autor only said that was made using JNA interface.
So, i'm studyng this piece of code and trying compile with success using NetBeans IDE and JNA, but seem that JNA interface that i have here ( 4.2.2 ) not have all methods and functions used on piece of code left by autor.
Are they:
GetProcAddress
VirtualAllocEx
VirtualFreeEx
So, i'm wanting some help here if possible, for try solved this trouble of missing of methods in JNA.
I had fixed big part these erros but still missing some methods in JNA like i will show following point to point with comments.
package inject;
//////////////////// JNA-4.2.2 /////////////////////
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.Tlhelp32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinDef.HMODULE;
import com.sun.jna.platform.win32.WinNT;
import com.sun.jna.platform.win32.WinNT.HANDLE;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.win32.W32APIOptions;
import java.io.File;
//////////////////////////////////////////////////
// Extracted from: https://github.com/warmuuh/AndroidCtx/tree/master/HotContext/src/luz/winapi
import inject.luz.winapi.constants.DwDesiredAccess;
import inject.luz.winapi.tools.Advapi32Tools;
import inject.luz.winapi.tools.Kernel32Tools;
import luz.winapi.api.exception.Kernel32Exception;
//////////////////////////////////////////////////////////////////////////////////////////////
public class Inject {
private static int GetPid(String proc){
int id = 0;
Kernel32 kernel32 = (Kernel32) Native.loadLibrary(Kernel32.class, W32APIOptions.UNICODE_OPTIONS);
Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference();
WinNT.HANDLE snapshot = kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));
try {
while (kernel32.Process32Next(snapshot, processEntry)) {
if (Native.toString(processEntry.szExeFile).equalsIgnoreCase(proc)) {
id = processEntry.th32ProcessID.intValue();
}
}
}
finally {
kernel32.CloseHandle(snapshot);
}
return id;
}
private static String findProcessByPID(int pid){
String name = "";
Kernel32 kernel32 = (Kernel32) Native.loadLibrary(Kernel32.class, W32APIOptions.UNICODE_OPTIONS);
Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference();
WinNT.HANDLE snapshot = kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));
try {
while (kernel32.Process32Next(snapshot, processEntry)) {
if (pid == processEntry.th32ProcessID.intValue()) {
name = processEntry.szExeFile.toString();
}
}
}
finally {
kernel32.CloseHandle(snapshot);
}
return name;
}
public static void inject(File dll, Integer pId) throws Kernel32Exception {
if(null == dll || !dll.exists() || !dll.isFile() || !dll.getName().endsWith(".dll"))
return;
String p = findProcessByPID(pId);
if(null == p) return;
Kernel32 kernel = Kernel32.INSTANCE;
HMODULE kernel32Pointer = kernel.GetModuleHandle("Kernel32");
// Cannot find "GetProcAddress"
Pointer loadLibraryAddress = kernel.GetProcAddress(kernel32Pointer, "LoadLibraryA");
HANDLE process = null;
DwDesiredAccess access = new DwDesiredAccess();
access.setPROCESS_ALL_ACCESS();
try {
Advapi32Tools.getInstance().enableDebugPrivilege(Kernel32Tools.getInstance().GetCurrentProcess());
} catch (Exception e) {
}
// Incompatible types "Pointer" and "HANDLE"
process = Kernel32Tools.getInstance().OpenProcess(access, false, pId);
String path = dll.getPath() + '\0';
byte[] bytes = path.getBytes();
int pathLength = bytes.length;
// Cannot find "VirtualAllocEx"
Pointer memoryDllPath = kernel.VirtualAllocEx(process, null, pathLength, Kernel32Tools.MEM_COMMIT, Kernel32Tools.PAGE_READWRITE);
Memory dllPathContent = new Memory(pathLength);
for(int i=0;i<pathLength;i++)
dllPathContent.setByte(i, bytes[i]);
IntByReference writeResult = new IntByReference();
boolean successWritting = kernel.WriteProcessMemory(process, memoryDllPath, dllPathContent, pathLength, writeResult);
if(!successWritting) {
kernel.CloseHandle(process);
return;
}
IntByReference threadId = new IntByReference();
// Pointer cannot be converted to "FOREIGN_THREAD_START_ROUTINE"
Pointer thread = kernel.CreateRemoteThread(process, null, 0, loadLibraryAddress, memoryDllPath, 0, threadId);
boolean res = false;
// Incompatible types "Pointer" and "HANDLE" //Cannot find "WAIT_TIMEOUT"
res = kernel.WaitForSingleObject(thread, Integer.MAX_VALUE) != Kernel32Tools.WAIT_TIMEOUT;
// Cannot find "VirtualFreeEx" method // Cannot find "MEM_RELEASE"
kernel.VirtualFreeEx(process, memoryDllPath, pathLength, Kernel32Tools.MEM_RELEASE);
kernel.CloseHandle(process);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println(GetPid("notepad.exe"));
}
}
Thank in advance by any suggestion or help :-)
JNA missing methods? It ain't so!
You just need to extend the library and add your own (and, ideally, also contribute the "missing" methods back to the JNA library so others can benefit.
Here is an example of how someone has mapped GetProcAddress.
Someone has mapped VirtualAllocEx here (although they should properly have extended Kernel32 rather than copied it entirely and edited portions)
I couldn't find an example of VirtualFreeEx within the same 15 seconds I found the others... doesn't mean it's not out there but after writing the others you shouldn't have much trouble writing it as well.

Exception: java.lang.NoClassDefFoundError: org.ehcache.CacheMangerBuilder

I'll preface this by saying "I have no idea what I'm doing" with java, let alone ehcache, but I'm trying to learn.
That said, I have this code I've written that ran fine until I added the ehcache stuff. I had been simply writing to and reading from files, which worked fine but slow, so I'm trying to speed things up by using cache instead.
When I run my program, I get the following error, and I don't understand what it's telling me is wrong:
Exception in thread "Connect thread - [6, 5]."
java.lang.NoClassDefFoundError: org.ehcache.CacheManagerBuilder
at com.ibm.tpf.internal.ZSTATEngine.doFilter(ZSTATEngine.java:24)
at com.ibm.tpf.etos.filter.FilterFramework.filterMessage(FilterFramework.java:229)
at com.ibm.tpf.etos.api.APIFramework.addMessage(APIFramework.java:304)
at com.ibm.tpf.etos.comm.ETOSConnection.addMessage(ETOSConnection.java:765)
at com.ibm.tpf.etos.comm.ETOSModel._connect(ETOSModel.java:528)
at com.ibm.tpf.etos.comm.ETOSModel$ConnectThread.run(ETOSModel.java:706)
Caused by: java.lang.NoClassDefFoundError:
org.ehcache.CacheMangerBuilder
at java.net.URLClassLoader.findClass(URLClassLoader.java:496)
at java.lang.ClassLoader.loadClass(ClassLoader.java:631)
at java.lang.ClassLoader.loadClass(ClassLoader.java:597)
... 6 more
I tried to mimic the cache code found on the ehcache 3.0 documentation page... but I must've done something horribly wrong. Anyone mind taking a look?
package com.ibm.tpf.internal;
import java.awt.Color;
import java.io.File;
import org.ehcache.*;
import org.ehcache.config.CacheConfigurationBuilder;
import com.ibm.tpf.etos.TPFFilter.*;
import com.ibm.tpf.etos.api.*;
import com.ibm.tpf.etos.filter.*;
public class ZSTATEngine implements ETOSFilterEngine {
FilterFramework fw = null;
String[] names = null;
public ZSTATEngine(FilterFramework filFW, String[] parms) {
super();
this.fw = filFW;
}
public MessageBlock doFilter(MessageBlock msgBlock) throws FilterRuntimeException {
File file = new File("{path omitted}\\FILTER.DAT");
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("csmpCache",CacheConfigurationBuilder.newCacheConfigurationBuilder().buildConfig(Long.class, String.class)).build(false);
cacheManager.init();
Cache<Long, String> csmpCache = cacheManager.getCache("csmpCache", Long.class, String.class);
if(msgBlock.getMsgID().equals("CSMP0097I")) {
csmpCache.put(1L, msgBlock.getMsg()); /* 1L is a key */
msgBlock.setSuppressed(TernarySwitch.ON);
}
else {
if(msgBlock.getFlag() == Constants.ETOS_ONE_MSG || msgBlock.getFlag() == Constants.ETOS_START_MSG) {
if(file.exists() && file.isFile()) {
String csmpValue = csmpCache.get(1L);
MessageBlock mbCSMP = new MessageBlock(csmpValue, Constants.ETOS_ONE_MSG);
mbCSMP.setForeground(Color.BLUE);
msgBlock.setForeground(Color.BLUE);
fw.addFilteredMessage(mbCSMP);
}
}
}
cacheManager.close();
return msgBlock; /* whatever gets returned is what the system prints */
}
private Color ColorStringInterpreter(String colorMsg) throws FilterRuntimeException {
if (colorMsg.toUpperCase().startsWith("TOS")) { /* if it starts with TOS, then we're using color names */
String[] colorParts = colorMsg.split("_",2);
String colorTxt = colorParts[1].toString().trim();
if (colorTxt.toUpperCase() != "NONE") {
Color finalColor = Colors.fromString(colorTxt);
return finalColor;
}
}
else {
String[] colorParts = colorMsg.split("_",3); /* otherwise we're using RGB values */
String sRed = colorParts[0].toString().trim();
String sGreen = colorParts[1].toString().trim();
String sBlue = colorParts[2].toString().trim();
int iRed = Integer.parseInt(sRed);
int iGreen = Integer.parseInt(sGreen);
int iBlue = Integer.parseInt(sBlue);
Color finalColor = new Color (iRed, iGreen, iBlue);
return finalColor;
}
return null;
}
public String getName() {
return null;
}
public void modifyState(Object[] newParams) throws FilterConfigurationException, FilterRuntimeException {
}
public boolean isActive() {
return false;
}
public void shutdown() {
}
}
Thank you for your time

How to retrieve a list of included client libs from a component in CQ?

Is it possible to determine, what client libs have been loaded prior to a component?
We are running multiple site backed by different Javascript frameworks. In order to run a single component across the board, it's not sufficient to just use
<cq:includeClientLib categories="blah"/>
We need to identify the respective framework (i.e. AngularJS, Vanilla, jQuery, blah) in order to facilitate the integration.
We are looking for a decent server side solution.
I haven't actually done this, but it would presumably be possible if you are buffering your output to clone the JspWriter buffer or examine it to see what it already contains. That sounds ugly to me, though. But this is decompiled code for how the cq:includeClientLib tag adds libraries to the output, which may show you how you can read back what was previously written:
package com.adobe.granite.ui.tags;
import com.day.cq.widget.HtmlLibraryManager;
import java.io.IOException;
import javax.servlet.ServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.scripting.SlingBindings;
import org.apache.sling.scripting.jsp.util.TagUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class IncludeClientLibraryTag extends TagSupport {
private static final long serialVersionUID = -3068291967085012331L;
private static final Logger log = LoggerFactory.getLogger(IncludeClientLibraryTag.class);
private String categories;
private String js;
private String css;
private String theme;
private Boolean themed;
public IncludeClientLibraryTag() {
}
public void setPageContext(PageContext pageContext) {
super.setPageContext(pageContext);
this.categories = null;
this.js = null;
this.css = null;
this.theme = null;
this.themed = null;
}
public void setCategories(String categories) {
this.categories = categories;
}
public void setJs(String js) {
this.js = js;
}
public void setCss(String css) {
this.css = css;
}
public void setTheme(String theme) {
this.theme = theme;
}
public void setThemed(boolean themed) {
this.themed = Boolean.valueOf(themed);
}
public int doEndTag() throws JspException {
SlingHttpServletRequest request = TagUtil.getRequest(this.pageContext);
HtmlLibraryManager libManager = this.getHtmlLibraryManager(request);
if(libManager == null) {
log.warn("<ui:includeClientLib>: Could not retrieve HtmlLibraryManager service, skipping inclusion.");
return 6;
} else {
JspWriter out = this.pageContext.getOut();
try {
if(this.categories != null) {
libManager.writeIncludes(request, out, toArray(this.categories));
} else if(this.theme != null) {
libManager.writeThemeInclude(request, out, toArray(this.theme));
} else if(this.js != null) {
if(this.themed != null) {
libManager.writeJsInclude(request, out, this.themed.booleanValue(), toArray(this.js));
} else {
libManager.writeJsInclude(request, out, toArray(this.js));
}
} else if(this.css != null) {
if(this.themed != null) {
libManager.writeCssInclude(request, out, this.themed.booleanValue(), toArray(this.css));
} else {
libManager.writeCssInclude(request, out, toArray(this.css));
}
}
return 6;
} catch (IOException var6) {
String libs = this.categories != null?"categories: " + this.categories:(this.theme != null?"theme: " + this.theme:(this.js != null?"js: " + this.js:(this.css != null?"css: " + this.css:"")));
throw new JspException("Could not include client library: " + libs, var6);
}
}
}
private HtmlLibraryManager getHtmlLibraryManager(ServletRequest request) {
SlingBindings bindings = (SlingBindings)request.getAttribute(SlingBindings.class.getName());
return (HtmlLibraryManager)bindings.getSling().getService(HtmlLibraryManager.class);
}
private static String[] toArray(String commaSeparatedList) {
if(commaSeparatedList == null) {
return new String[0];
} else {
String[] split = commaSeparatedList.split(",");
for(int i = 0; i < split.length; ++i) {
split[i] = split[i].trim();
}
return split;
}
}
}
I think the best solution may be to use the client library dependencies or embed attributes in your library, though, or let the client-side JavaScript test if a library is present (ex. test if the jQuery object is undefined) and then take appropriate action. In other words, let the client side determine the final rendering based on what libraries exist on in the client. It sounds like this may not be possible for your situation, though.
dependencies: This is a list of other client library categories on
which this library folder depends. For example, given two
cq:ClientLibraryFolder nodes F and G, if a file in F requires another
file in G in order to function properly, then at least one of the
categories of G should be among the dependencies of F.
embed: Used to > embed code from other libraries. If node F embeds nodes G and H, the
resulting HTML will be a concetration of content from nodes G and H.

Running the SimulationStarter class in the AlgoTrader

I am trying to run the SimulationStarted class with the moving average strategy in the open source edition of AlgoTrader.
When I start the SimulationStarter I get ArrayIndexOutOfBoundsException.
I am trying to run it through eclipse. From AlgoTrader they run it with the following command
java.exe -cp target/classes;../../AlgoTrader/code/target/classes;../../AlgoTrader/code/lib/*;target/* -Dsimulation=true -DdataSource.dataSet=1year com.algoTrader.starter.SimulationStarter simulateWithCurrentParams
So is it even possible to run it through eclipse or this is the only way?
If anyone has any ideas or suggestions it will be much appreciated.
Here is the code for the SimulationStarter and ServiceLocator classes.
package com.algoTrader.starter;
import org.apache.commons.math.*;
import org.apache.log4j.Logger;
import com.algoTrader.ServiceLocator;
import com.algoTrader.service.SimulationServiceImpl;
import com.algoTrader.util.MyLogger;
public class SimulationStarter {
private static Logger logger = MyLogger.getLogger(SimulationServiceImpl.class.getName());
public static void main(String[] args) throws ConvergenceException, FunctionEvaluationException {
ServiceLocator.serverInstance().init("beanRefFactorySimulation.xml");
if ("simulateWithCurrentParams".equals(args[0])) {
ServiceLocator.serverInstance().getSimulationService().simulateWithCurrentParams();
} else if ("optimizeSingleParamLinear".equals(args[0])) {
String strategyName = args[1];
for (int i = 2; i < args.length; i++) {
String[] params = args[i].split(":");
String parameter = params[0];
double min = Double.parseDouble(params[1]);
double max = Double.parseDouble(params[2]);
double increment = Double.parseDouble(params[3]);
ServiceLocator.serverInstance().getSimulationService().optimizeSingleParamLinear(strategyName, parameter, min, max, increment);
}
}
ServiceLocator.serverInstance().shutdown();
}
}
And the service locator class
package com.algoTrader;
import com.algoTrader.entity.StrategyImpl;
import com.algoTrader.util.ConfigurationUtil;
public class ServiceLocator {
private static boolean simulation = ConfigurationUtil.getBaseConfig().getBoolean("simulation");
private static String strategyName = ConfigurationUtil.getBaseConfig().getString("strategyName");
public static CommonServiceLocator commonInstance() {
if (!simulation && !StrategyImpl.BASE.equals(strategyName)) {
return RemoteServiceLocator.instance();
} else {
return ServerServiceLocator.instance();
}
}
public static ServerServiceLocator serverInstance() {
if (!simulation && !StrategyImpl.BASE.equals(strategyName)) {
throw new IllegalArgumentException("serverInstance cannot be called from the client");
} else {
return ServerServiceLocator.instance();
}
}
}
To Fix this error you will need to open the Run Configuraitons in Eclipse and Add the program Arguments and the VM Arguments and the ArrayIndexOutOfBoundsException will be gone.
The bad news are that there is another error: 2014-01-22 11:15:35,771 ERROR JDBCExceptionReporter Access denied for user 'algouser'#'localhost' (using password: YES)
Which I will be investigating now
In order to run AlgoTrader you need to have a database (MySQL) and configure DB in the source code of AlgoTrader. Without DB AlgoTrader does not work.

PhoneGap Android copy to clipboard plugin implementation

I'm trying to use this plugin in my application. I've never written a plugin and this is my first time trying to use one in my Phonegap program. I had to try and change a whole bunch of stuff in the java file to get rid of the errors. When I click a button on my screen, I get an error "Uncaught ReferenceError: cordova is not defined at file:///android_asset/www/js/clipboardmanager.js:2". No idea what that means or how to change that. I'll try and paste everything so hopefully it's easier to find my error.
structure:
src
-->com.example.basket
-->MainActivity.java
-->com.saaticiouglu.phonegap.ClipboardManagerPlugin
-->ClipboardManagerPlugin.java
ClipboardManagerPlugin.java:
package com.saatcioglu.phonegap.ClipboardManagerPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.ClipboardManager;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.PluginResult;
#SuppressWarnings("deprecation")
public class ClipboardManagerPlugin extends CordovaPlugin {
private static final String actionCopy = "copy";
private static final String actionPaste = "paste";
private static final String errorParse = "Couldn't get the text to copy";
private static final String errorUnknown = "Unknown Error";
private ClipboardManager mClipboardManager;
#SuppressLint("NewApi") #Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
{
// If we do not have the clipboard
if(mClipboardManager == null) {
mClipboardManager = (ClipboardManager) cordova.getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
}
// Copy
if (action.equals(actionCopy)) {
String arg = "";
try {
arg = (String) args.get(0);
mClipboardManager.setText(arg);
} catch (JSONException e) {
callbackContext.error( errorParse);
} catch (Exception e) {
callbackContext.error( errorUnknown);
}
callbackContext.success();
// Paste
} else if (action.equals(actionPaste)) {
String arg = (String) mClipboardManager.getText();
if (arg == null) {
arg = "";
}
PluginResult copy_ret = new PluginResult(PluginResult.Status.OK, arg);
callbackContext.sendPluginResult(copy_ret);
callbackContext.success();
} else {
callbackContext.error("invalid action");
return false;
}
return true;
}
}
I had to use the Surpress warnings because setText and getText were giving me errors...and they are still crossed out in my file. But no errors there now...
clipboardmanager.js:
window.clipboardManagerCopy = function(str, success, fail) {
cordova.exec(success, fail, "ClipboardManagerPlugin", "copy", [str]);
};
window.clipboardManagerPaste = function(success, fail) {
cordova.exec(success, fail, "ClipboardManagerPlugin", "copy", []);
};
I referenced to the JS file in my index.html:
$('button').on('click', function(){
window.clipboardManagerCopy(
"the text to copy",
function(r){alert("copy is successful")},
function(e){alert(e)}
);
});
I just want to get a simple alert to see that it works. Thanks for taking the time to help out. Please help me fix this!!!

Categories

Resources