Exception in thread "main" java.lang.Error: Unresolved compilation problems: JNI4net - jni4net

I am working with JNI4net and although the libraries and installed in the build path and eclipse recognizes them, it still gives me run time error. Why could that be in your opinion? Here is the code.
import net.sf.jni4net.*;
import java.io.IOException;
import java.lang.String;
import system.*;
import system.Object;
import system.io.TextWriter;
import system.collections.IDictionary;
import system.collections.IEnumerator;
/**
* #author Pavel Savara (original)
*/
public class Program {
public static void main(String[] args) throws IOException {
// create bridge, with default setup
// it will lookup jni4net.n.dll next to jni4net.j.jar
//Bridge.setVerbose(true);
Bridge.setVerbose(true);
Bridge.init();
// here you go!
Console.WriteLine("Hello .NET world!\n");
// OK, simple hello is boring, let's play with System.Environment
// they are Hashtable realy
final IDictionary variables = system.Environment.GetEnvironmentVariables();
// let's enumerate all keys
final IEnumerator keys = variables.getKeys().GetEnumerator();
while (keys.MoveNext()) {
// there hash table is not generic and returns system.Object
// but we know is should be system.String, so we could cast
final system.String key = (system.String) keys.getCurrent();
Console.Write(key);
// this is automatic conversion of JVM string to system.String
Console.Write(" : ");
// we use the hashtable
Object value = variables.getItem(key);
// and this is JVM toString() redirected to CLR ToString() method
String valueToString = value.toString();
Console.WriteLine(valueToString);
}
// Console output is really TextWriter on stream
final TextWriter writer = Console.getOut();
writer.Flush();
}
}
AND here is the message I get!
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Bridge cannot be resolved
Bridge cannot be resolved
Console cannot be resolved
IDictionary cannot be resolved to a type
system cannot be resolved
IEnumerator cannot be resolved to a type
system cannot be resolved to a type
system cannot be resolved to a type
Console cannot be resolved
Console cannot be resolved
Console cannot be resolved
TextWriter cannot be resolved to a type
Console cannot be resolved
at Program.main(Program.java:37)

To make your life easier, I am going to share my findings here. Read Martin Serrano's answer to my question. It will help you understand what needs to be done. Then go to jni4net's website and download their example zip folder. Extract that. There is an example there called myCSharpDemoCalc. Replace your dll with myCSharpDemoCalc.dll (inside work folder) and then run generateProxies.cmd (be sure to edit this file to your dll name) and run.cmd. Then go to the work folder and run build.cmd (edit name) to create your JAR file. It might not spit out the j4n.dll you probably need to twik the path yourself. Use this JAR file. This was the easiest way to create a JAR file from a third party dll for me.

Related

Dart build runner generate one dart file with content

I am working on a dart package with includes over 200 models and at the moment i have to write manually one line of "export" for each model, to make the models available for everyone who uses this package.
I want the build runner to generate one dart file which contains every export definition.
Therefore I would create an annotation "ExportModel". The builder should search for each class annotated with this annotation.
I tried creating some Builders, but they will generate a *.g.dart file for each class that is annotated. I just want to have one file.
Is where a way to create a builder that runs only once and creates a file at the end ?
The short answer to your question of a builder that only runs once and creates a single file in the package is to use r'$lib$' as the input extension. The long answer is that to find the classes that are annotated you probably want an intermediate output to track them.
I'd write this with 2 builders, one to search for the ExportModel annotation, and another to write the exports file. Here is a rough sketch with details omitted - I haven't tested any of the code here but it should get you started on the right path.
Builder 1 - find the classes annotated with #ExportModel().
Could write with some utilities from package:source_gen, but can't use LibraryBuilder since it's not outputting Dart code...
Goal is to write a .exports file next to each .dart file which as the name of all the classes that are annotated with #ExportModel().
class ExportLocatingBuilder implements Builder {
#override
final buildExtensions = const {
'.dart': ['.exports']
};
#override
Future<void> build(BuildStep buildStep) async {
final resolver = buildStep.resolver;
if (!await resolver.isLibrary(buildStep.inputId)) return;
final lib = LibraryReader(await buildStep.inputLibrary);
final exportAnnotation = TypeChecker.fromRuntime(ExportModel);
final annotated = [
for (var member in lib.annotatedWith(exportAnnotation)) element.name,
];
if (annotated.isNotEmpty) {
buildStep.writeAsString(
buildStep.inputId.changeExtension('.exports'), annotated.join(','));
}
}
}
This builder should be build_to: cache and you may want to have a PostProcessBuilder that cleans up all the outputs it produces which would be specified with applies_builder. You can use the FileDeletingBuilder to cheaply implement the cleanup. See the FAQ on temporary outputs and the angular cleanup for example.
Builder 2 - find the .exports files and generate a Dart file
Use findAssets to track down all those .exports files, and write an export statement for each one. Use a show with the content of the file which should contain the names of the members that were annotated.
class ExportsBuilder implements Builder {
#override
final buildExtensions = const {
r'$lib$': ['exports.dart']
};
#override
Future<void> build(BuildStep buildStep) async {
final exports = buildStep.findAssets(Glob('**/*.exports'));
final content = [
await for (var exportLibrary in exports)
'export \'${exportLibrary.changeExtension('.dart').uri}\' '
'show ${await buildStep.readAsString(exportLibrary)};',
];
if (content.isNotEmpty) {
buildStep.writeAsString(
AssetId(buildStep.inputId.package, 'lib/exports.dart'),
content.join('\n'));
}
}
}
This builder should likely be build_to: source if you want to publish this file on pub. It should have a required_inputs: [".exports"] to ensure it runs after the previous builder.
Why does it need to be this complex?
You could implement this as a single builder which uses findAssets to find all the Dart files. The downside is that rebuilds would be much slower because it would be invalidated by any content change in any Dart file and you'd end up parsing all Dart code for a change in any Dart code. With the 2 builder approach then only the individual .exports which come from a changed Dart file need to be resolved and rebuilt on a change, and then only if the exports change will the exports.dart file be invalidated.
Older versions of build_runner also didn't support using the Resolver to resolve code that isn't transitively imported from the input library. Recent version of build_runner have relaxed this constraint.

Ignore Varargs Warnings In Javac

I want to escalate the missing serialversionUID warning to an error and fail my build when it occurs in javac.
I have added the following to my ant task:
<compilerarg value="-Xlint:serial"/>
<compilerarg value="-Werror"/>
However, the build also fails with varargs warnings:
non-varargs call of varargs method with inexact argument type for last parameter;
cast to java.lang.Object for a varargs call
cast to java.lang.Object[] for a non-varargs call and to suppress this warning
I tried changing the javac task to
<compilerarg value="-Xlint:-varargs"/>
<compilerarg value="-Xlint:serial"/>
<compilerarg value="-Werror"/>
However, it made no difference. How do I make the compiler ignore these warnings and only fail on the serialversionUID?
I am using Ant 1.9.4 and tried with Javac 1.6u37, 1.7u79 and 1.8u92
Example class:
package com.stackoverflow.compiler;
import java.io.Serializable;
public class Main implements Serializable {
public static void foo(Object... args) {
System.out.println("Test foo");
}
public static void main(String[] args) {
// is args supposed to be an array of objects
// or the only element in an array?
foo(args);
}
}
It seems that the warning you have is not related to the -Xlint:varargs option
According to javac reference the varargs option for -Xlint:
Warns about unsafe usages of variable arguments (varargs) methods, in particular, those that contain non-reifiable arguments
The documentation says that the following code:
public class ArrayBuilder {
public static <T> void addToList (List<T> listArg, T... elements) {
for (T x : elements) {
listArg.add(x);
}
}
}
should produce the warning:
warning: [varargs] Possible heap pollution from parameterized vararg type T
The actual warning I get (using javac 1.8.0_65) is:
warning: [unchecked] Possible heap pollution from parameterized vararg type T
(i.e unchecked instead of varargs)
The warning you got can be caused by code like this:
public static void foo(Object... args) {...}
public static void main(String[] args) {
// is args supposed to be an array of objects
// or the only element in an array?
foo(args);
}
That warning went away only using -Xlint:none option, but then -Xlint:serial does nothing. So it seems what you want is not possible.
I know the question is about javac, but let me still mention that ecj can be configured to meet your requirement: simply say -err:serial on the command line.
With that option this source file
public class Serial implements java.io.Serializable {}
will trigger this compiler output
----------
1. ERROR in /tmp/Serial.java (at line 1)
public class Serial implements java.io.Serializable {}
^^^^^^
The serializable class Serial does not declare a static final serialVersionUID field of type long
----------
1 problem (1 error)
Other warnings are not affected by that option. In particular, you could complete suppress the varargs warning by adding -warn:-varargsCast. This isn't necessary because a warning will never let your build fail. But if you really don't want to see this even as a warning, the full command line would look like this:
ecj -err:serial -warn:-varargsCast Main.java
See the JDT FAQ for using ecj in automated builds, incl. ant.

Call libc function from JNA

I use a C library from Java through JNA and one function does not flush properly (since the output appear all at once on program end). I have tried Java side System.out.flush(); with no luck.
In brief, I would like to call C fflush(stdout) from Java. With JNA already there (thus would prefer if no additional library) and without C to write.
I am aware of JNA Library mapping as in this question but that seems overkill to me.
The JNA library wrapping way code is actually not so heavy (at least for the flush all behavior).
protected interface CLibrary extends Library
{
static CLibrary clib = (CLibrary) Native.loadLibrary ("c", CLibrary.class);
int fflush (Pointer stream);
}
/* ... */
CLibrary.clib.fflush (null);
JNA also offer late binding method and these oneliners will do what you want
NativeLibrary.getInstance ("c").getFunction ("fflush").invokeInt (new Object[]{0});
// even shorter
Function.getFunction ("c", "fflush").invokeInt (new Object[]{0});
The tedious part comes when you want to limit flushing to stdout. You have to deal with vendor-specific code (stdout is either defined as a macro expanding to an array, Amtel avr-libc, to a function call, Microsoft msvcrt, or a pointer in GNU libc).
For the libc, you might use (two lines for legibility)
Pointer stdout = NativeLibrary.getInstance ("c").getGlobalVariableAddress ("stdout").getPointer (0);
Function.getFunction ("c", "fflush").invokeInt (new Object[]{stdout});
Adding this answer for Win32 / Win64 users, complementing FabienAndre's for GNU libc.
Selectively flushing the stdout stream calling the system's c library's fflush method via jna is hard and cumbersome. As FabienAndre already mentioned, it is difficult to get a hold of the stdout macro definition. For msvcrt (the Win32 / Win64 C library) it is defined via a function call to __iob_func(); the latter returning a pointer to an array of FILE structures. At index 0 is stdin, index 1 is stdout and index 2 is stderr. So for flushing stdout you even need to know the size of the FILE structure, of course, it is different for Win32 and Win64 ...
The following example is tested under Win64 but ought to work under Win32. It was inspired by the thread JNA solutions to catch stdout/stderr of DLL.
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
import com.sun.jna.Pointer;
public class JnaTest {
public interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary) Native.loadLibrary("msvcrt" , CLibrary.class);
Pointer __iob_func();
void printf(String format, Object... args);
int fflush (Pointer stream);
}
public static void main(String[] args) {
int sizeOfFileStructure = Platform.is64Bit() ? 48 : 32;
Pointer stdout = CLibrary.INSTANCE.__iob_func().share(sizeOfFileStructure);
CLibrary.INSTANCE.printf("Hello, World\n");
CLibrary.INSTANCE.fflush(stdout);
}
}

Switching from Rhino to Nashorn

I have a Java 7 project which makes a lot of use of Javascript for scripting various features. Until now I was using Rhino as script engine. I would now like to move to Java 8, which also means that I will replace Rhino by Nashorn.
How compatible is Nashorn to Rhino? Can I use it as a drop-in replacement, or can I expect that some of my scripts will not work anymore and will need to be ported to the new engine? Are there any commonly-used features of Rhino which are not supported by Nashorn?
One problem is that Nashorn can no longer by default import whole Java packages into the global scope by using importPackage(com.organization.project.package);
There is, however, a simple workaround: By adding this line to your script, you can enable the old behavior of Rhino:
load("nashorn:mozilla_compat.js");
Another problem I ran into is that certain type-conversions when passing data between java and javascript work differently. For example, the object which arrives when you pass a Javascript array to Java can no longer be cast to List, but it can be cast to a Map<String, Object>. As a workaround you can convert the Javascript array to a Java List in the Javascript code using Java.to(array, Java.type("java.util.List"))
To use the importClass method on JDK 8, we need to add the following command:
load("nashorn:mozilla_compat.js");
However, this change affect the execution on JDK 7 (JDK does not gives support to load method).
To maintain the compatibility for both SDKs, I solved this problem adding try/catch clause:
try{
load("nashorn:mozilla_compat.js");
}catch(e){
}
Nashorn can not access an inner class when that inner class is declared private, which Rhino was able to do:
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Test {
public static void main(String[] args) {
Test test = new Test();
test.run();
}
public void run() {
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
Inner inner = new Inner();
engine.put("inner", inner);
try {
engine.eval("function run(inner){inner.foo(\"test\");} run(inner);");
} catch (ScriptException e) {
e.printStackTrace();
}
}
private class Inner {
public void foo(String msg) {
System.out.println(msg);
}
}
}
Under Java8 this code throws following exception:
javax.script.ScriptException: TypeError: kz.test.Test$Inner#117cd4b has no such function "foo" in <eval> at line number 1
at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:564)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:548)
I noticed that Rhino didn't have a problem with a function called 'in()' (although 'in' is a reserved JavaScript keyword).
Nashorn however raise an error.
Nashorn cannot call static methods on instances! Rhino did this, therefore we had to backport Rhino to Java 8 (Here's a short summary: http://andreas.haufler.info/2015/04/using-rhino-with-java-8.html)
Nashorn on Java8 does not support AST. So if you have Java code that inspects the JS source tree using Rhino's AST mechanism , you may have to rewrite it (using regex maybe) once you port your code to use Nashorn.
I am talking about this API https://mozilla.github.io/rhino/javadoc/org/mozilla/javascript/ast/AstNode.html
Nashorn on Java9 supports AST though.
One feature that is in Rhino and not Nashorn: exposing static members through instances.
From http://nashorn-dev.openjdk.java.narkive.com/n0jtdHc9/bug-report-can-t-call-static-methods-on-a-java-class-instance : "
My conviction is that exposing static members through instances is a
sloppy mashing together of otherwise separate namespaces, hence I
chose not to enable it.
I think this is deeply wrong. As long as we have to use two different constructs to access the same java object and use package declarations unnecessarily in javascript, code becomes harder to read and write because cognitive load increases. I will rather stick to Rhino then.
I have not found a workaround for this obvious "design bug" yet.

Resolving a type without registering first - prism 4 and Untiy

First of all I would like to remark I am new with the concept of prism, DI and containers. I am looking on one of the code samples provided with the Prism Library:
The code simply injects a view with the "Hello World" string (in a TextBlock element) to a region in the shell.
When the application starts-up, it creates a new BootStrapper instance, which creates and initializes the shell:
public class Bootstrapper : UnityBootstrapper
{
protected override DependencyObject CreateShell()
{
return Container.Resolve<Shell>();
}
protected override void InitializeShell()
{
base.InitializeShell();
Application.Current.RootVisual = (UIElement)this.Shell;
}
protected override void ConfigureModuleCatalog()
{
base.ConfigureModuleCatalog();
ModuleCatalog moduleCatalog = (ModuleCatalog)this.ModuleCatalog;
moduleCatalog.AddModule(typeof(HelloWorldModule.HelloWorldModule));
}
}
My question refers to the method CreateShell(). I couldnt find nowhere in the supplied code (including not in a configuration file or any xaml file...) where do they register the type Shell, and even if it was registered - the supplies Shell class doesnt implement any interface... what is the meaning of resolving a specific type?
the Shell implementation:
public partial class Shell : UserControl
{
public Shell()
{
InitializeComponent();
}
}
This looks like a magic to me, so I tried to create my own type (MyType) and resolve it the same way:
Container.Resolve<MyType>();
By setting a breakepoint inside MyType constructor, I saw that it DID resolved MyType. Can somebody please explain to me how does it work?
These couple of threads should answer your question:
http://compositewpf.codeplex.com/Thread/View.aspx?ThreadId=230051
Does unity just make clasess with out needing anything registered?
Additionally, if you are eager to get more detail into how Unity can do this, simple download Unity 2.0 and open the source code that is provided with the installer.
I hope this helps.
Thanks,
Damian
You do not need to register a type you want to resolve. You need to register the dependencies of a type, that you want to resolve. In this case, the Shell doesn't need any dependencies, so you can resolve it simply. But for an example (not really), if your shell getting an interface IService as a parameter, then you must register IService, before you resolve Shell.
Otherwise you will get Dependency Resolution Failed Exception. In Prism 4.1 it will be swallowed silently due to TryResolve.

Resources