include PKCS11 library in Java - java

I have PCKS11 dll and so files for my token.and i want to use [jacknji11][1] library.
my problem is how can i import the dll OR so files to my project.
i use System.loadLibrary("parskey11"); to import my library but i get below Error :
Exception in thread "main" java.lang.UnsatisfiedLinkError: org.pkcs11.jacknji11.jna.JNANative.C_InitToken(Lcom/sun/jna/NativeLong;[BLcom/sun/jna/NativeLong;[B)I
at org.pkcs11.jacknji11.jna.JNANative.C_InitToken(Native Method)
at org.pkcs11.jacknji11.jna.JNA.C_InitToken(JNA.java:119)
at org.pkcs11.jacknji11.C.InitToken(C.java:235)
at org.pkcs11.jacknji11.CE.InitToken(CE.java:272)
at com.mmdt.Main.main(Main.java:13)
i just copy my libparskey11.so file to jni folder in project and use below code :
private static final long INITSLOT = 0;
public static void main(String[] args) {
CE.InitToken(INITSLOT, "pincode".getBytes(), "TEST".getBytes());
long session = CE.OpenSession(INITSLOT, CKS.RW_PUBLIC_SESSION, null,
null);
CE.Login(session, CKU.SO, "pincode".getBytes());
CE.InitPIN(session, "pincode2".getBytes());
CE.Logout(session);
CE.Login(session, CKU.USER, "pincode".getBytes());
byte[] somenewpin = "somenewpin".getBytes();
CE.SetPIN(session, "pincode2".getBytes(), somenewpin);
CE.SetPIN(session, somenewpin, "pincode2".getBytes());
}

Related

Java - URI is not hierarchical error appears only in the exported JAR, not in Eclipse

I have a Java program that is able to change the wallpaper taking in input an image using WINAPI.
Everything works fine when I run it inside Eclipse IDE, but when I run the JAR I got the error:
Caused by: java.lang.IllegalArgumentException: URI is not hierarchical
public class Main {
//INIT USER32 for WINAPI
public static interface User32 extends Library {
User32 INSTANCE = (User32) Native.loadLibrary("user32",User32.class,W32APIOptions.DEFAULT_OPTIONS);
boolean SystemParametersInfo (int one, int two, String s ,int three);
}
public static void main(String[] args) throws IOException, URISyntaxException {
//Change wallpaper
System.out.println("Change wallpaper");
URL url = Main.class.getResource("/resources/img.jpg");
File f = new File(url.toURI());
String path = f.getPath();
User32.INSTANCE.SystemParametersInfo(0x0014, 0, path , 1);
}
}
The image is shipped within the JAR, so maybe the error is related to this since the program is not able to correctly read to URL inside the JAR.
Is there a way to solve this?
A jar file is just a compressed file when the resource is bundled as a jar java will be treated as a single file, which means it will not access to your resources.
try using this instead getResourceAsStream(...);

ImportError: No Module named demiso in Jython

I'm new to the Jython and I'm trying to run a python class using Jython in Java. But I'm running into some issues.
The Java class that I've defined:
public class DemistoCalls {
PythonInterpreter interpreter = null;
public DemistoCalls()
{
PythonInterpreter.initialize(System.getProperties(),
System.getProperties(), new String[0]);
this.interpreter = new PythonInterpreter();
}
void execfile( final String fileName )
{
this.interpreter.execfile(fileName);
}
PyInstance createClass( final String className, final String opts )
{
return (PyInstance) this.interpreter.eval(className + "(" + opts + ")");
}
public static void main(String[] args) {
DemistoCalls demistoCalls = new DemistoCalls();
demistoCalls.execfile("C:\\Users\\AlokNath\\Desktop\\Demisto_Project\\demisto-py-master\\demisto\\SimpleConnect.py");
}
}
The SampleConnect.py file that I'm trying to run:
import sys
sys.path.append("C:\Users\AlokNath\Desktop\Demisto_Project\demisto-py-
master\demisto")
import demisto
While Running the java file, I'm getting this error:
File "C:\Users\AlokNath\Desktop\Demisto_Project\demisto-py-master\demisto\SimpleConnect.py", line 3, in <module>
import demisto
ImportError: No module named demisto
Although I've defined the "demisto" module in the system path and checked that the system path in python contains the appropriate path to Jython 2.7.lb2 Library. I'm not sure where am I going wrong. Any help is appreciated.
Regards,
Alok
I found a solution to the import error problem. We need to copy the missing module to the “site-packages” folder under "modeler-installation/lib/jython/Lib". This will resolve the dependency problem.

Project throwing IOException (File Not Found) when jar is run

I've made a project in java, using Eclipse.
Here is the project structure:
When I'm running the project in Eclipse as a java application, it runs perfectly fine.
Now, I need to export it as a jar. So, I created the jar using the method described in 3rd answer on this link (answered by Fever):
Failing to run jar file from command line: “no main manifest attribute”
Here is the output of jar tf EventLogger.jar:
META-INF/MANIFEST.MF
com/
com/project/
com/project/eventLogger/
com/project/eventLogger/KafkaConsumerGroup.class
com/project/eventLogger/KafkaProducer.class
com/project/eventLogger/ConsumeConfig.class
com/project/eventLogger/ConsumerThread.class
com/project/eventLogger/Formatter.class
com/project/eventLogger/Execute.class
com/project/eventLogger/Config.class
com/project/eventLogger/package-info.class
com/project/eventLogger/ProdConfig.class
com/project/eventLogger/FormatConfig.class
resources/
resources/Config.properties
resources/ConsumerConfig.properties
resources/FormatterConfig.properties
resources/ProducerConfig.properties
resources/log4j.properties
Here is the manifest file:
Manifest-Version: 1.0
Built-By: vishrant
Class-Path: lib/json-simple-1.1.1.jar lib/junit-4.10.jar lib/hamcrest-
core-1.1.jar lib/kafka_2.9.2-0.8.2.2.jar lib/jopt-simple-3.2.jar lib/
kafka-clients-0.8.2.2.jar lib/log4j-1.2.16.jar lib/lz4-1.2.0.jar lib/
metrics-core-2.2.0.jar lib/slf4j-api-1.7.6.jar lib/snappy-java-1.1.1.
7.jar lib/slf4j-log4j12-1.6.1.jar lib/zkclient-0.3.jar lib/zookeeper-
3.4.6.jar lib/jline-0.9.94.jar lib/netty-3.7.0.Final.jar lib/scala-li
brary-2.9.2-RC3.jar
Build-Jdk: 1.8.0_74
Created-By: Maven Integration for Eclipse
Main-Class: com.project.eventLogger.Execute
and, here is the exception:
java.io.FileNotFoundException: ConsumerConfig.properties (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at com.project.eventLogger.ConsumeConfig.loadPropertiesFile(ConsumeConfig.java:34)
at com.project.eventLogger.ConsumeConfig.<clinit>(ConsumeConfig.java:42)
at com.project.eventLogger.Execute.main(Execute.java:18)
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.project.eventLogger.Execute.main(Execute.java:18)
Caused by: java.lang.NullPointerException
at com.project.eventLogger.ConsumeConfig.<clinit>(ConsumeConfig.java:47)
... 1 more
Seeing the exception, it is clear that it is not able to load ConsumerConfig.properties which is being done in ConsumeConfig.java.
Here is ConsumeConfig.java:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Properties;
/**
* #author vishrant
*
*/
public class ConsumeConfig {
public static String zookeeper;
public static String balance;
public static String bootstrap_servers;
public static String zk_session_to;
public static String zk_sync;
public static String auto_commit;
public static String[] topics;
private static String kafka_bin;
private static final String PROPERTIES_FILE_PATH = "src/main/resources/ConsumerConfig.properties";
private static Properties loadPropertiesFile() throws IOException {
Properties properties = new Properties();
InputStream in = new FileInputStream(PROPERTIES_FILE_PATH);
properties.load(in);
return properties;
}
static {
Properties property = null;
try {
property = loadPropertiesFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
zookeeper = property.getProperty("ZOOKEEPER");
balance = property.getProperty("BALANCE");
bootstrap_servers = property.getProperty("BOOTSTRAP_SERVERS");
zk_session_to = property.getProperty("ZK_SESSION_TO");
zk_sync = property.getProperty("ZK_SYNC_TIME");
auto_commit = property.getProperty("AUTO_COMMIT_INTERVAL");
topics = property.getProperty("CONSUMER_TOPICS").split(",");
kafka_bin = property.getProperty("KAFKA_BIN_PATH");
}
}
Can someone tell me what is the problem and how to resolve this?
This runs perfectly well when run in Eclipse itself.
EDIT1:
Now, the exception is:
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.project.eventLogger.Execute.main(Execute.java:18)
Caused by: java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:434)
at java.util.Properties.load0(Properties.java:353)
at java.util.Properties.load(Properties.java:341)
at com.project.eventLogger.ConsumeConfig.loadPropertiesFile(ConsumeConfig.java:35)
at com.project.eventLogger.ConsumeConfig.<clinit> (ConsumeConfig.java:42)
... 1 more
line no 35:
props.load(resourceStream);
This is the code now:
private static final String PROPERTIES_FILE_PATH = "ConsumerConfig.properties";
private static Properties loadPropertiesFile() throws IOException {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Properties props = new Properties();
InputStream resourceStream = loader.getResourceAsStream(PROPERTIES_FILE_PATH);
props.load(resourceStream);
return props;
}
I see the following problems to be the cause:
The jar file is not created correctly for a maven project because the directory resources will normally be not copied to the target directory as is, i.e., instead of
resources/Config.properties
it should look like without the resources directory:
Config.properties
directly under the root directory of the jar file.
The second point is you are using the following in your code
private static final String PROPERTIES_FILE_PATH = "src/main/resources/ConsumerConfig.properties";
This path will not be seen outside of your IDE (in this case Eclipse) because src/main/resources should not exist in the jar file as you could see in the list of your jar file.
The last point is, you should use getResourceAsStream() of the class loader as Vikrant Kashyap already pointed.
try this
// Change Your File Path First.
private static final String PROPERTIES_FILE_PATH = "ConsumerConfig.properties";
private static Properties loadPropertiesFile() throws IOException {
Properties properties = new Properties();
// First way to load ResourceAsStream.
// ClassLoader loader = Thread.currentThread().getContextClassLoader();
// InputStream resourceStream = loader.getResourceAsStream(PROPERTIES_FILE_PATH);
// Second way to load ResourceAsStream.
InputStream resourceStream = ConsumeConfig.class.getResourceAsStream(PROPERTIES_FILE_PATH);
properties.load(resourceStream);
return properties;
}

jni4net failed to load DLLs in Java app

I'm trying to modify the jni4net sample code MyCSharpDemoCalc, and make the sample as a bridge between a .Net DLL and the Java layer. Here is the C# code:
using System;
using Dynamsoft.DotNet.TWAIN;
namespace MyCSharpDemoCalc
{
public interface ICalc
{
int MySuperSmartFunctionIDontHaveInJava(string question);
bool IsShowUI();
}
public class DemoCalc : ICalc
{
private readonly Random r = new Random();
private DynamicDotNetTwain dynamicDotNetTwain;
public DemoCalc()
{
dynamicDotNetTwain = new Dynamsoft.DotNet.TWAIN.DynamicDotNetTwain();
}
public int MySuperSmartFunctionIDontHaveInJava(string question)
{
if (question == "Answer to the Ultimate Question of Life, the Universe, and Everything")
{
return 42;
}
return r.Next();
}
public bool IsShowUI()
{
return dynamicDotNetTwain.IfShowUI;
}
}
}
In order to build it successfully, I added the following references:
System.Windows.Forms
DynamicDotNetTWAIN
Then typed in the command
proxygen.exe MyCSharpDemoCalc.dll -wd work
to generate MyCSharpDemoCalc.j4n.jarand MyCSharpDemoCalc.j4n.dll.
Now, I can import DynamicDotNetTWAIN.dll, MyCSharpDemoCalc.j4n.dll, jni4net.n.w64.v20-0.8.6.0.dll, jni4net.n-0.8.6.0.dll, jni4net.j-0.8.6.0.jar and MyCSharpDemoCalc.j4n.jar to Java project.
Java code:
import net.sf.jni4net.Bridge;
import java.io.IOException;
import mycsharpdemocalc.DemoCalc;
import mycsharpdemocalc.ICalc;
public class Program {
public static void main(String arsg[]) throws IOException {
Bridge.setClrVersion("v20");
Bridge.init();
Bridge.LoadAndRegisterAssemblyFrom(new java.io.File("DynamicDotNetTWAIN.dll"));
Bridge.LoadAndRegisterAssemblyFrom(new java.io.File("MyCSharpDemoCalc.j4n.dll")); // crashed
ICalc calc = new DemoCalc();
final int result = calc.MySuperSmartFunctionIDontHaveInJava("Answer to the Ultimate Question of Life, the Universe, and Everything");
System.out.printf("Answer to the Ultimate Question is : " + result);
System.out.printf("If show UI : " + calc.IsShowUI());
}
}
When I tried to run the application, it crashed at
Bridge.LoadAndRegisterAssemblyFrom(new
java.io.File("MyCSharpDemoCalc.j4n.dll"));
Exception in thread "main" System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
at System.Reflection.Module._GetTypesInternal(StackCrawlMark& stackMark)
at System.Reflection.Assembly.GetTypes()
at net.sf.jni4net.utils.Registry.RegisterAssembly(Assembly assembly, Boolean bindJVM, ClassLoader classLoader)
at net.sf.jni4net.Bridge.RegisterAssembly(Assembly assembly, ClassLoader classLoader)
at net.sf.jni4net.Bridge.LoadAndRegisterAssemblyFromClassLoader(File assemblyFile, ClassLoader classLoader)
at net.sf.jni4net.Bridge.LoadAndRegisterAssemblyFrom(File assemblyFile)
at net.sf.jni4net.__Bridge.LoadAndRegisterAssemblyFrom3(IntPtr __envp, JniLocalHandle __class, JniLocalHandle assemblyFile)
at net.sf.jni4net.Bridge.LoadAndRegisterAssemblyFrom(Native Method)
at com.main.Program.main(Program.java:68)
How can I fix it? Thanks!
The JNI4NET will attempt to load the image from where the JNI4NET libraries were located at, the only workaround (AFAIK) was to copy the whole libraries to your source directory, and compile your package using the copied libraries, then it will work.

Why can't java find my class?

I have a class that compiles without error. The class has a main method. But when I try to run it on ubuntu linux from the classes' directory I get a class not found error. I am pretty sure I am missing something dead obvious but I don't see it.
Here is my ls operation:
zookeeper#zookeeper-virtual-machine:~/zookeeper-3.4.5/programs$ ls
CreateGroup.java LsGroup.class LsGroup.java zookeeper-3.4.5.jar
Here is what happens when I to run LsGroup
zookeeper#zookeeper-virtual-machine:~/zookeeper-3.4.5/programs$ java -cp "zookeeper-3.4.5.jar" LsGroup
Exception in thread "main" java.lang.NoClassDefFoundError: LsGroup
Caused by: java.lang.ClassNotFoundException: LsGroup
at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
Could not find the main class: LsGroup. Program will exit.
Here is the code for LsGroup
package org.zookeeper;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.KeeperState;
public class LsGroup implements Watcher {
private static final int SESSION_TIMEOUT = 5000;
private ZooKeeper zk;
private CountDownLatch connectedSignal = new CountDownLatch(1);
public void connect(String hosts) throws IOException, InterruptedException {
zk = new ZooKeeper(hosts, SESSION_TIMEOUT, this);
connectedSignal.await();
}
#Override
public void process(WatchedEvent event) { // Watcher interface
if (event.getState() == KeeperState.SyncConnected) {
connectedSignal.countDown();
}
}
public void ls(String groupName) throws KeeperException, InterruptedException {
String path = "/" + groupName;
try {
List<String> children = zk.getChildren(path, false);
for (String child : children) {
System.out.println(path+"/"+child);
System.out.println(zk.getChildren(path +"/"+ child, false));
}
} catch (KeeperException.NoNodeException e) {
System.out.printf("Group %s does not exist\n", groupName);
System.exit(1);
}
}
public void close() throws InterruptedException {
zk.close();
}
public static void main(String[] args) throws Exception {
LsGroup lsGroup = new LsGroup();
lsGroup.connect(args[0]);
lsGroup.ls(args[1]);
lsGroup.close();
}
}
The original problem was that your class was in a package, but you were trying to load it as if it weren't in a package. You'd normally organize your source code to match your package hierarchy, then from the root of the hierarchy, you'd run something like:
java -cp .:zookeeper-3.4.5.jar org.zookeeper.LsGroup
Now that you've temporarily worked around the package issue by moving the code out of a package, the next problem is that the current directory isn't in the classpath. So instead of this:
java -cp "zookeeper-3.4.5.jar" LsGroup
You want:
java -cp .:zookeeper-3.4.5.jar LsGroup
Once you've got that working, you should move the classes back into packages, as per normal Java best practice.
You could remove the package declaration:
package org.zookeeper;
...or just place your LsGroup class in org/zookeeper directory.
The class file is supposed to live in a path like:
org/zookeeper/LsGroup.class
The -cp must include the directory that contains the org/ directory. Then you can
java -cp parent-of-org org.zookeeper.LsGroup
The message "wrong name: org/zookeeper/LsGroup" means, you have to respect the package structure of Java. Use the following directory structure:
./org/zookeeper/LsGroup.class
Then launch java org.zookeeper.LsGroup from within the current directory. The package separator "." will be translated to corresponding directory.
Your files are not under package org.zookeeper
You should be running your class from ~/zookeeper-3.4.5/org/zookeeper
Otherwise JVM won't find the classes to load.
Your class is part of the org.zookeeper package but you keep it in the root folder of your project (/zookeeper-3.4.5/programs).
The qualified name of the package member and the path name to the file are parallel (see Managing Source and Class Files), so if your package is org.zookeeper the class file should be kept in /zookeeper-3.4.5/programs/org/zookeeper
You made two mistakes:
1) You tried to run java LsGroup but you have to use the complete name including packages java org.zookeeper.LsGroup
2) your directory structure is not correct: the package org.zookeeper corresponds with the directory structure ./org/zookeeper/
If you change the directory structure and then run java from the top of this directory structure it should work

Categories

Resources