I work with the JPOS library. I am trying to get a list of all com-ports using the RXTXCommDriver class. An error occurs when calling the main native method, which gets a list of all ports.
java.lang.UnsatisfiedLinkError: javax.comm.RXTXCommDriver.nativeGetVersion()Ljava/lang/String;
public class RXTXCommDriver implements CommDriver
{
private final static boolean debug = true;
private final static boolean devel = false;
private final static boolean noVersionOutput = "true".equals( System.getProperty( "gnu.io.rxtx.NoVersionOutput" ) );
static
{
if(debug ) System.out.println("RXTXCommDriver {}");
System.loadLibrary( "rxtxSerial" );
/*
Perform a crude check to make sure people don't mix
versions of the Jar and native lib
Mixing the libs can create a nightmare.
It could be possible to move this over to RXTXVersion
but All we want to do is warn people when first loading
the Library.
*/
String JarVersion = RXTXVersion.getVersion();
String LibVersion;
try {
LibVersion = RXTXVersion.nativeGetVersion();
} catch ( Error UnsatisfiedLinkError )
{
// for rxtx prior to 2.1.7
LibVersion = nativeGetVersion();
}
if ( devel )
{
if ( ! noVersionOutput )
{
System.out.println("Stable Library");
System.out.println("=========================================");
System.out.println("Native lib Version = " + LibVersion );
System.out.println("Java lib Version = " + JarVersion );
}
}
Related
I'm new here and I'm currently working on a standalone source code parser with eclipse-jdt. I have currently an issue that I can't get any further with. The source code parser should write (in this case) a compiler message in a log file:
The following code is from a visitor:
for (IProblem problem : problems) {
if (problem.isError()) {
final String msg = "Problem count: " + problems.length + " in " + resource.getAbsolutePath()
+ "\n\tERROR: " + problem.getSourceLineNumber() + " > " + problem.getMessage();
logger.log(Level.INFO, msg);
continue; // do not count errors
}
// ...
logCompilerMessage(getFullQualifiedName(), mainAuthor, problem);
}
For an example, while parsing the method readData:
package testproj.pckg.billing;
//...
public class Bill {
private boolean readData(MODETYPE modeType) {
// MODETYPE is an enum in other class but in the same package
}
}
The program will "classified" the enum MODETYPE as a error which is in class Bill2.java:
package testproj.pckg.billing;
// ...
public class Bill2 {
// ...
}
enum MODETYPE {
// ...
}
The output will be looking like this:
Problem count: 8 in E:\ws\preview\project\src\testproj\pckg\billing\Bill.java
ERROR: 1925 > MODETYPE cannot be resolved to a type
And this is my parse method:
private void parse(ProjectInfo project, File resource) {
final ASTParser parser = ASTParser.newParser(AST.JLS11);
parser.setResolveBindings(true);
parser.setBindingsRecovery(true);
parser.setStatementsRecovery(true);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setCompilerOptions(project.getCompilerOptions());
final Path sourcePath = Paths.get(resource.toURI());
final char[] source = sourceToChar(sourcePath);
if (source == null) {
return;
}
parser.setSource(source);
parser.setUnitName(resource.getName());
final String[] sources = project.getProjectRelatedSources();
final String[] classpaths = project.getProjectRelatedClasspaths();
final String[] encoders = listOfEncoders(sources);
parser.setEnvironment(classpaths, sources, encoders, true);
// accept visitor(s)
}
EDIT: I forgot to show you my getCompilerOptions method:
private Map<String, String> getCompilerOptions(ProjectInfo project) {
final Map<String, String> list = JavaCore.getOptions();
list.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_11);
list.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_11);
list.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.ENABLED);
list.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
final Config config = new Config(project.getProjectPath() + File.separator + ".settings",
"org.eclipse.jdt.core.prefs");
for (String key : config.keySet()) {
list.put(key, config.value(key));
}
return list;
}
Config is just a handler for property file which I used to initialize the program. In this case, I read the property file org.eclipse.jdt.core.prefs from the eclipse project and return it as a Map.
Everything is working and correctly detected on our IDE but somehow not on the standalone parser.
Can someone help me with it? Thank you in advice!
Best regards,
lftdbmr
I have to work with an already existing Eclipse RAP application which contains of two features and around 40 dependencies.
Since the Eclipse RAP doesn't have a preStartup() method I call the update procedure in the RAP's start() method:
public class MyApplication implements IApplication
{
#Override
public Object start( IApplicationContext context ) throws Exception
{
P2Util.update();
...
}
}
The IProvisioningAgent is not null, the IMetadataRepositoryManager and IArtifactRepositoryManager are correctly initialized.
public static boolean configureRepository( IProvisioningAgent agent )
{
String repo = "file:///c:/export/repository/"; // TODO HERE!
log.debug( "Initiliazing Repository Managers" );
IMetadataRepositoryManager metadataManager = ( IMetadataRepositoryManager ) agent.getService( IMetadataRepositoryManager.SERVICE_NAME );
IArtifactRepositoryManager artifactManager = ( IArtifactRepositoryManager ) agent.getService( IArtifactRepositoryManager.SERVICE_NAME );
URI uri;
try
{
uri = new URI( repo );
}
catch ( URISyntaxException e1 )
{
log.error( "Unexpected URISyntaxException, the specified path is not a valid URI", e1 ); //$NON-NLS-1$
return false;
}
if ( metadataManager == null )
{
log.error( "IMetadataRepositoryManager instance is null!" );
return false;
}
metadataManager.addRepository( uri );
log.debug( "Added repository to MetadataManager: " + repo );
if ( artifactManager == null )
{
log.error( "IArtifactRepositoryManager instance is null!" );
return false;
}
artifactManager.addRepository( uri );
log.debug( "Added repository to ArtifactManager: " + repo );
return true;
}
Still one problem occurs all the time after I call checkForUpdates().
public static IStatus checkForUpdates( IProvisioningAgent agent ) throws OperationCanceledException
{
log.info( "Checking for new updates in repository" );
ProvisioningSession session = new ProvisioningSession( agent );
UpdateOperation operation = new UpdateOperation( session );
IStatus status = operation.resolveModal( new NullProgressMonitor() );
return status;
}
It returns the following status:
Status OK: org.eclipse.equinox.p2.operations code=10001 Your original request has been modified. null children=[]
I have already checked the flag "Support software installation in the launched application" in my run configuration, the problem persists.
I'm experimenting with Neo4J via Embedded Java API.
My Build path seems ok (no Exceptions during runtime).
When I create some nodes and relations, I can query it directly after it with success.
But after shutting down and re-run my programm, i'm only getting the data I created in the new runtime and none of them before.
But if I look at my directory, I see, that the size has grown with each runtime, I perform a creating of data.
Here's my code:
public static void main(String[] args)
{
GraphDatabaseService gdb = new GraphDatabaseFactory().newEmbeddedDatabase( "/mytestdb/" );
create( gdb );
query( gdb );
gdb.shutdown();
}
private static void query( GraphDatabaseService gdb )
{
StringLogger sl = StringLogger.wrap( new Writer()
{
#Override
public void write( char[] arg0, int arg1, int arg2 ) throws IOException
{
for( int i=arg1; i<=arg2; i++ ) System.out.print( arg0[i] );
}
#Override
public void flush() throws IOException
{}
#Override
public void close() throws IOException
{}
} );
ExecutionEngine ee = new ExecutionEngine( gdb, sl );
ExecutionResult result = ee.execute( "MATCH (p:Privilleg) RETURN p" );
System.out.println( result.dumpToString() );
}
private static void create( GraphDatabaseService gdb )
{
Transaction tx = gdb.beginTx();
Node project = gdb.createNode( MyLabels.Project );
Node user = gdb.createNode( MyLabels.User );
Node priv1 = gdb.createNode( MyLabels.Privilleg );
Node priv2 = gdb.createNode( MyLabels.Privilleg );
user.setProperty( "name", "Heinz" );
user.setProperty( "email", "heinz#gmx.net" );
priv1.setProperty( "name", "Allowed to read all" );
priv1.setProperty( "targets", Short.MAX_VALUE );
priv1.setProperty( "read", true );
priv1.setProperty( "write", false );
priv2.setProperty( "name", "Allowed to write all" );
priv2.setProperty( "targets", Short.MAX_VALUE );
priv2.setProperty( "read", false );
priv2.setProperty( "write", true );
project.setProperty( "name", "My first project" );
project.setProperty( "sname", "STARTUP" );
user.createRelationshipTo( priv1, MyRelationships.UserPrivilleg );
user.createRelationshipTo( priv2, MyRelationships.UserPrivilleg );
priv1.createRelationshipTo( project, MyRelationships.ProjectPrivilleg );
priv2.createRelationshipTo( project, MyRelationships.ProjectPrivilleg );
tx.success();
}
Your code doesn't close the transaction. Typically you use a try-with-resources block:
try (Transaction tx=gdb.beginTx()) {
// do stuff in the graph
tx.success();
}
Since Transaction is AutoClosable its close() method will be called implicitly upon leaving the code block. If (for whatever) reason you decide not to use try-with-resources, be sure to explicitly call close().
On a different notice: your code uses ExecutionEngine. Since Neo4j 2.2 you directly call gdb.execute(myCypherString) instead.
Thank you! This works.
Also, before I closed the transaction, it takes about 20 seconds to shuting down the db. This also is now less than a second.
Background :
I started playing with Groovy recently and am trying to embed a groovy script engine in an eclipse plugin to let my customers develop their own GUI extensions inside my eclipse-based product. This is very similar to the success story published on codehaus's website.
Problem
The groovy script (let's call it "main_eclipse.groovy") run from the eclipse plugin by a GroovyScriptEngine throws when trying to load a groovy class ("SwtGuiBuilder"), with the following error :
BUG! Queuing new source whilst already iterating. Queued source is 'file:/home/nicolas/workspace/groovy-test/src/gui/SwtGuiBuilder.groovy'
Question
Did anyone run into the same problem ? How can it be fixed ?
Any help will be highly appreciated !
Some observations :
When using the groovy interpreter instead of a GroovyScriptEngine java object, I have no problem using my SwtGuiBuilder class (see script "main_groovy" here below).
My problem does not seem to be a classpath issue, since the file containing my SwtGuiBuilder class is mentioned in the thrown exception.
The error message is mentioned in two reported groovy bugs, GRECLIPSE-429 and GRECLIPSE-1037. I did not fully get the technicals details, but those bugs seemed to be related to performance issues when loading lots of classes, which is not relevant in my situation...
Details
SampleView.java
public class SampleView
{
public SampleView() { super(); }
public void createPartControl(Composite parent)
{
String groovyScript = null;
String [] groovyPath = null;
boolean shall_exit = false;
do
{ // ask user for params
GroovyLocationDialog groovyLocationDialog= new GroovyLocationDialog(parent.getShell() );
int return_code = groovyLocationDialog.open();
if ( return_code != Window.OK )
shall_exit = true;
else
{
groovyScript= groovyLocationDialog.getInputScriptName();
groovyPath = groovyLocationDialog.getInputScriptPath();
// run it
ScriptConnector scriptConnector = new ScriptConnector(parent);
try { scriptConnector.runGuiComponentScript( groovyPath, groovyScript); }
catch (Exception e) { e.printStackTrace(); }
System.out.println("script finished");
}
}
while ( ! shall_exit );
}
ScriptConnector.java
public class ScriptConnector
{
private String[] roots;
private Composite window;
private Binding binding;
public ScriptConnector( Composite window )
{
this.window = window;
Binding scriptenv = new Binding(); // A new Binding is created ...
scriptenv.setVariable("SDE", this);
scriptenv.setVariable("WINDOW", this.window); // ref to current window
this.binding = scriptenv;
}
public void runGuiComponentScript(final String[] groovyPath, final String scriptName)
{
GroovyScriptEngine gse = null;
this.roots = groovyPath;
try
{
// instanciating the script engine with current classpath
gse = new GroovyScriptEngine( roots, this.getClass().getClassLoader() );
gse.run(scriptName, binding); // ... and run specified script
}
catch (Exception e) { e.printStackTrace(); }
catch (Throwable t) { t.printStackTrace(); }
}
}
main_eclipse.groovy
package launcher;
import org.eclipse.swt.SWT
import org.eclipse.swt.widgets.*
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.RowLayout as Layout
// This import will fail...
import gui.SwtGuiBuilder;
WINDOW.layout = new Layout(SWT.VERTICAL);
def builder = new SwtGuiBuilder(WINDOW);
builder.Label ( style=SWT.NONE, text = 'Simple demo of Groovy and SWT')
builder.Button( style=SWT.PUSH, text = 'Click me' , action = { println "Click !" } )
SwtGuiBuilder.groovy
package gui;
import org.eclipse.swt.events.*
import org.eclipse.swt.widgets.Button
import org.eclipse.swt.widgets.Composite
import org.eclipse.swt.widgets.Label
class SwtGuiBuilder
{
private Composite _parent
public SwtGuiBuilder(Composite parent) { _parent = parent }
public void Button( style = SWT.PUSH, text= null, action = null )
{
def btn = new Button(_parent, style)
if ( text != null )
btn.text = text
if (action != null)
btn.addSelectionListener( new SelectionAdapter() { void widgetSelected( SelectionEvent event ) { action(); } } );
}
public void Label( style = SWT.NONE, text = '' )
{
def lbl = new Label(_parent, style)
lbl.text = text
}
}
main_groovy.groovy
package launcher;
import org.eclipse.swt.SWT
import org.eclipse.swt.widgets.*
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.RowLayout as Layout
// ... But this import is handled properly !
import gui.SwtGuiBuilder;
def display = new Display()
def WINDOW = new Shell(display)
WINDOW.text = 'Groovy / SWT Test';
WINDOW.layout = new Layout(SWT.VERTICAL);
def builder = new SwtGuiBuilder(WINDOW);
builder.Label ( style=SWT.NONE, text = 'Simple demo of Groovy and SWT')
builder.Button( style=SWT.PUSH, text = 'Click me' , action = { println "Ya clicked me !" } )
WINDOW.pack();
WINDOW.open();
while (!WINDOW.disposed) {
if (!WINDOW.display.readAndDispatch())
WINDOW.display.sleep();
}
Stack trace
BUG! Queuing new source whilst already iterating. Queued source is 'file:/home/nicolas/workspace/groovy-test/src/gui/SwtGuiBuilder.groovy'
at org.codehaus.groovy.control.CompilationUnit.addSource(CompilationUnit.java:460)
at org.codehaus.groovy.control.CompilationUnit.addSource(CompilationUnit.java:433)
at groovy.util.GroovyScriptEngine$ScriptClassLoader$3.findClassNode(GroovyScriptEngine.java:195)
at org.codehaus.groovy.control.ClassNodeResolver.resolveName(ClassNodeResolver.java:124)
at org.codehaus.groovy.control.ResolveVisitor.resolveToOuter(ResolveVisitor.java:863)
at org.codehaus.groovy.control.ResolveVisitor.resolve(ResolveVisitor.java:377)
at org.codehaus.groovy.control.ResolveVisitor.visitClass(ResolveVisitor.java:1407)
at org.codehaus.groovy.control.ResolveVisitor.startResolving(ResolveVisitor.java:202)
at org.codehaus.groovy.control.CompilationUnit$1.call(CompilationUnit.java:713)
at org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(CompilationUnit.java:1015)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:647)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:596)
at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:279)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:258)
at groovy.util.GroovyScriptEngine$ScriptClassLoader.doParseClass(GroovyScriptEngine.java:247)
at groovy.util.GroovyScriptEngine$ScriptClassLoader.parseClass(GroovyScriptEngine.java:229)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:244)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:202)
at groovy.util.GroovyScriptEngine.loadScriptByName(GroovyScriptEngine.java:514)
at groovy.util.GroovyScriptEngine.createScript(GroovyScriptEngine.java:564)
at groovy.util.GroovyScriptEngine.run(GroovyScriptEngine.java:551)
My configuration :
Linux Ubuntu 14.04 x86
Groovy Version: 2.3.2
JVM: 1.7.0_55
Eclipse Kepler SR2 - Build 20140224-0627
Eclipse Groovy plugin v2.0.7
Instead of GroovyScriptEngine, I've used the GroovyShell class (groovy code below but easy enough to change back to java), CompilerConfiguration allows you to specify the classpath.
def config = new CompilerConfiguration(classpath: classpath)
def binding = new Binding()
def result = new GroovyShell(binding, config).evaluate("""
def foo='bar'
""")
I want to make some changes on active desktop wallpaper like adding watermark.
For that I need to get the path of the active wallpaper. Adding the watermark I can do.
This can be done using JNA library, but I can't access the file path.
The way to obtain the current desktop wallpaper could different based on the operating system, for windows 7 it can be obtained from following registry path,
HKEY_CURRENT_USER\Control Panel\Desktop\Wallpaper
to read the registry path you can use the method described in following question
read/write to Windows Registry using Java
As Low Flying Pelican and ee said,
HKEY_CURRENT_USER\Control Panel\Desktop
contains the key Wallpaper which has a pointer to the wallpaper. For the command prompt, you can use
reg query "HKEY_CURRENT_USER\Control Panel\Desktop" /v Wallpaper
to get the location, or using this for native java support:
Runtime.getRuntime().exec('reg query "HKEY_CURRENT_USER\Control Panel\Desktop" /v Wallpaper');
Using JNA library:
implementation("net.java.dev.jna:jna-platform:5.12.1")
I was able to get the current Wallpaper path like this (tested on Windows 11):
Java:
import com.sun.jna.platform.win32.*;
import com.sun.jna.platform.win32.WinReg.HKEYByReference;
public class Main {
public static final String REGISTRY_PATH = "Control Panel\\Desktop";
public static final String REGISTRY_Key = "WallPaper";
public static void main(String[] args) {
var hKey = new HKEYByReference();
var registryAccessResult = openRegistryKey(hKey);
validate(registryAccessResult);
var wallpaperPath = getWallpaperPath();
System.out.println(wallpaperPath);
}
public static int openRegistryKey(HKEYByReference hKey) {
return Advapi32.INSTANCE.RegOpenKeyEx(
WinReg.HKEY_CURRENT_USER,
REGISTRY_PATH,
0,
WinNT.KEY_READ,
hKey
);
}
public static void validate(int registryAccessResult) {
if (registryAccessResult != W32Errors.ERROR_SUCCESS) {
throw new Win32Exception(registryAccessResult);
}
}
public static String getWallpaperPath() {
return Advapi32Util.registryGetStringValue(
WinReg.HKEY_CURRENT_USER,
REGISTRY_PATH,
REGISTRY_Key
);
}
}
Kotlin:
const val REGISTRY_PATH = "Control Panel\\Desktop"
const val REGISTRY_Key = "WallPaper"
fun main() {
val hKey = HKEYByReference()
openRegistryKey(hKey).validate()
val wallpaperPath = getWallpaperPath()
println(wallpaperPath)
}
fun openRegistryKey(hKey: HKEYByReference) =
Advapi32.INSTANCE.RegOpenKeyEx(
WinReg.HKEY_CURRENT_USER,
REGISTRY_PATH,
0,
WinNT.KEY_READ,
hKey
)
fun RegistryAccessResult.validate() =
takeIf { it == W32Errors.ERROR_SUCCESS }
?: throw Win32Exception(this)
fun getWallpaperPath(): String =
Advapi32Util.registryGetStringValue(
WinReg.HKEY_CURRENT_USER,
REGISTRY_PATH,
REGISTRY_Key
)
You can also listen for wallpaper changes and get its new path:
waitForWallpaperChange(hKey).validate() // Waits until wallpaper is changed
val newWallpaper = getWallpaperPath()
fun waitForWallpaperChange(hKey: HKEYByReference) =
Advapi32.INSTANCE.RegNotifyChangeKeyValue(
hKey.value,
false,
WinNT.REG_NOTIFY_CHANGE_LAST_SET,
null,
false
)