No COM ports identified with usb4java - serial-port

I have the following routine that is the entry point for accessing serial ports in the usb4java API running in windows. Any ideas what can be wrong.
import javax.comm.*
public class SimpleJSComRead
public static void main(String[] args) {
portList = CommPortIdentifier.getPortIdentifiers();
if (portList.nextElement()==null) System.out.println("Is Null");
}
}
Concurrently, this works using jssc. I'm able to read valid data through this interface.
import jssc.SerialPort;
import jssc.SerialPortException;
public class SimpleJSComRead {
public static void main(String[] args) {
SerialPort serialPort = new SerialPort("COM6");
try { serialPort.openPort();
} catch (SerialPortException e) {
e.printStackTrace();
}
if (serialPort.isOpened()) System.out.println("opened successfully");
try { serialPort.closePort();
} catch (SerialPortException e) {
e.printStackTrace();
}
}
}

I tracked down the fact that the javax.comm library is not fully implemented or supported.
I find it strange that a basic function like reading from a serial port should be a difficult task for Java whereas hosting web applications is duplicated by various APIs. I expect serial communication is well supported in Python and C++ as these are more used by the scientific community.
The additional solution I found was to utilize RXTX API... one and two . The process involves downloading the zipped distribution and extracting the dlls and jars to some library site on your FileSystem. Then declare the dependency to the Jar file. For example in Gradle
compile files( 'C:/..path../lib/jars/RXTXcomm.jar').
and setting the dll library path and loading the dll
System.setProperty("java.library.path", "C:/..path../lib/dlls_x64")
System.loadLibrary("rxtxSerial")
Finally, the serial API is not in javax.comm package, but in the gnu.io package.
import gnu.io.CommPortIdentifier
import io.FileMgr
//this one is based on RXTX and dlls are in library (gnu.io)
fun main(args: Array<String>) {
FileMgr.setDllLibraryPath("C:/..path../lib/dlls_x64")
System.loadLibrary("rxtxSerial")
val portList = CommPortIdentifier.getPortIdentifiers()
while (portList.hasMoreElements()) {
val x = portList.nextElement() as CommPortIdentifier
println("Port Name = " + x.name + ", type= " + x.portType)
}
if (portList.nextElement() == null) println("Is Null")
}
fun setDllLibraryPath(resourceStr: String) {
try {
System.setProperty("java.library.path", resourceStr)
//System.setProperty("java.library.path", "/lib/x64");//for example
val fieldSysPath =
ClassLoader::class.java.getDeclaredField("sys_paths")
fieldSysPath.isAccessible = true
fieldSysPath.set(null, null)//next time path is accessed, the new path
will be imported
} catch (ex: Exception) {
ex.printStackTrace()
throw RuntimeException(ex)
}
}

Related

How to reload apache commons configurations2 properties

can anyone guide me on how to perform a reload of an apache commons configuration2 properties. I'm unable to find any implementation of this anywhere. The apache docs are a bit too abstract. This is what I have so far but it's not working.
CombinedConfiguration cc = new CombinedConfiguration();
Parameters params = new Parameters();
File configFile = new File("config.properties");
File emsFile = new File("anotherconfig.properties");
ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration> configBuilder =
new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
.configure(params.fileBased()
.setFile(configFile));
PeriodicReloadingTrigger reloadTrg = new PeriodicReloadingTrigger(configBuilder.getReloadingController(), null, 5, TimeUnit.SECONDS);
reloadTrg.start();
cc.addConfiguration(configBuilder.getConfiguration());
FileBasedConfigurationBuilder<FileBasedConfiguration> emsBuilder =
new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
.configure(params.properties()
.setFile(emsFile));
cc.addConfiguration(emsBuilder.getConfiguration());
DataSource ds = EmsDataSource.getInstance().getDatasource(this);
BasicConfigurationBuilder<DatabaseConfiguration> dbBuilder =
new BasicConfigurationBuilder<DatabaseConfiguration>(DatabaseConfiguration.class);
dbBuilder.configure(
params.database()
.setDataSource(ds)
.setTable("EMS_CONFIG")
.setKeyColumn("KEY")
.setValueColumn("VALUE")
);
cc.addConfiguration(dbBuilder.getConfiguration());
The configuration obtained from a builder is not updated automatically. You need to get the configuration from the builder every time you read it.
From Automatic Reloading of Configuration Sources:
One important point to keep in mind when using this approach to reloading is that reloads are only functional if the builder is used as central component for accessing configuration data. The configuration instance obtained from the builder will not change automagically! So if an application fetches a configuration object from the builder at startup and then uses it throughout its life time, changes on the external configuration file become never visible. The correct approach is to keep a reference to the builder centrally and obtain the configuration from there every time configuration data is needed.
use following code:
#Component
public class ApplicationProperties {
private PropertiesConfiguration configuration;
#PostConstruct
private void init() {
try {
String filePath = PropertiesConstants.PROPERTIES_FILE_PATH;
System.out.println("Loading the properties file: " + filePath);
configuration = new PropertiesConfiguration(filePath);
//Create new FileChangedReloadingStrategy to reload the properties file based on the given time interval
FileChangedReloadingStrategy fileChangedReloadingStrategy = new FileChangedReloadingStrategy();
fileChangedReloadingStrategy.setRefreshDelay(PropertiesConstants.REFRESH_DELAY);
configuration.setReloadingStrategy(fileChangedReloadingStrategy);
} catch (ConfigurationException e) {
e.printStackTrace();
}
}
public String getProperty(String key) {
return (String) configuration.getProperty(key);
}
public void setProperty(String key, Object value) {
configuration.setProperty(key, value);
}
public void save() {
try {
configuration.save();
} catch (ConfigurationException e) {
e.printStackTrace();
}
}
}

Windows Store Application Place SQLite File in LocalState Folder

I am building a Windows 8 application using sql-net and mvvmcross for data access to a sqlite database. This would be applicable to any Win-8 or Win-Phone app.
I need to install an existing sqlite file on app start.
When using the connection you use syntax such as this
public FlashCardManager(ISQLiteConnectionFactory factory, IMvxMessenger messenger)
{
_messenger = messenger;
_connection = factory.Create("Dictionary.sqlite");
_connection.CreateTable<FlashCardSet>();
_connection.CreateTable<FlashCard>();
}
public void CreateCard(FlashCard flashCard)
{
_connection.Insert(flashCard);
}
That connection creates a file in: C:\Users\USER\AppData\Local\Packages\793fd702-171e-474f-ab3b-d9067c58709b_ka9b83fa3fse2\LocalState
My application uses an existing sqlite database file that I have created. I need to place it in this folder when the application is installed. How would I go about doing this?
Thanks,
JH
Make sure you have the database file you want your app to start off with in one of your apps folders (as in the folders visible in visual studios solution explorer). For this example I'll call this folder "Assets"
All you need to do then is copy this file to the LocalState folder the first time your app runs. This can be done in App.xaml.cs
private async void InitializeAppEnvironment()
{
try
{
if (!(await AppHelper.ExistsInStorageFolder(AppHelper.localFolder, dbName)))
{
StorageFile defaultDb = await AppHelper.installedLocation.GetFileAsync("Assets\\" + dbName);
await defaultDb.CopyAsync(AppHelper.localFolder);
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e);
}
}
I made an AppHelper class to simplify accessing the app data folders, here's the parts I used above:
static class AppHelper
{
public static StorageFolder installedLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;
public static StorageFolder localFolder = ApplicationData.Current.LocalFolder;
public static async Task<bool> ExistsInStorageFolder(this StorageFolder folder, string fileName)
{
try
{
await folder.GetFileAsync(fileName);
return true;
}
catch (FileNotFoundException)
{
return false;
}
}
}
For a more detailed response on MVVM cross I found the current discussion about cross platform file placement in this discussion: Link
The current thought is that you have to inject platform specific code for this sort of functionality.

Hosting SignalR with self host in Windows Service

I am new by signalR and Owin and need help.
I wrote all my signalR code in a library [My hub will be self hosted]. Then i referenced that lib from a windows service application, installed the Package "Microsoft.Owin.Host.HttpListener" in the windows service application and tried to execute it.
I am getting that wired exception:
Sequence contains no matching element
I tested my Library in a winForm application and it worked correctly.
I have no idea why i am getting that.
Update: Code example:
In My Library "myLib"
private IDisposable host;
private bool Start()
{
try
{
string url = "http://localhost:5000/";
host = SelfHost.Host(url);
}
catch (Exception ex)
{
log.WriteLine("************HOSTING FAILED ********************************* ex.ToString():"+ ex.ToString()+
" Ex.StackTrace: "+ex.StackTrace +" EX.Message: " + ex.Message + "***************");
}
}
private bool Stop()
{
if (host != null)
{
host.Dispose();
}
}
My SelfHost class:
class SelfHost
{
public static IDisposable Host(string url)
{
return WebApplication.Start<SelfHost>(url);
}
public void Configuration(IAppBuilder app)
{
// Turn cross domain on
var config = new HubConfiguration { EnableCrossDomain = true };
// This will map out to http://localhost:8080/signalr by default
app.MapHubs(config);
}
}
after creating an object from this lib in my windows service application:
myLib l = new myLib();
i implements the OnStart() of the windows Service which starts a thread that calls the Start()-function from myLib:
protected override void OnStart(string[] args)
{
Thread t = new Thread(new ThreadStart(this.StartServiceThread));
t.CurrentCulture = new System.Globalization.CultureInfo("en-US");
t.Start();
}
private void StartServiceThread()
{
l.Start();
}
Output [Ex-Details]
************HOSTING FAILED *********************************
ex.ToString():
System.InvalidOperationException: Sequence contains no matching element
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
at Microsoft.Owin.Hosting.ServerFactory.DefaultServerFactoryLoader.Load(String serverName)
at Microsoft.Owin.Hosting.KatanaEngine.ResolveServerFactory(StartContext context)
at Microsoft.Owin.Hosting.KatanaEngine.Start(StartContext context)
at Microsoft.Owin.Hosting.Starter.DirectHostingStarter.Start(StartOptions options)
at Microsoft.Owin.Hosting.KatanaStarter.Start(StartOptions options)
at Microsoft.Owin.Hosting.WebApplication.Start[TStartup](IServiceProvider services, StartOptions options)
at Microsoft.Owin.Hosting.WebApplication.Start[TStartup](StartOptions options)
at Microsoft.Owin.Hosting.WebApplication.Start[TStartup](String url)
at SelfHost.Host(String url) in SelfHost.cs:line 29
at myLib.Start() in myLib.cs:line 381
Ex.StackTrace:
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
at Microsoft.Owin.Hosting.ServerFactory.DefaultServerFactoryLoader.Load(String serverName)
at Microsoft.Owin.Hosting.KatanaEngine.ResolveServerFactory(StartContext context)
at Microsoft.Owin.Hosting.KatanaEngine.Start(StartContext context)
at Microsoft.Owin.Hosting.Starter.DirectHostingStarter.Start(StartOptions options)
at Microsoft.Owin.Hosting.KatanaStarter.Start(StartOptions options)
at Microsoft.Owin.Hosting.WebApplication.Start[TStartup](IServiceProvider services, StartOptions options)
at Microsoft.Owin.Hosting.WebApplication.Start[TStartup](StartOptions options)
at Microsoft.Owin.Hosting.WebApplication.Start[TStartup](String url)
at SelfHost.Host(String url) in SelfHost.cs:line 29
at myLib.Start() in myLib.cs:line 381
EX.Message: Sequence contains no matching element***************
Thanks in Advance!
I figured out what the problem was. I wrote myLib Code two months ago and was testing it using the winForms Application that i also wrote 2 months ago.
But yesterday i installed the new Owin Packages in my windows service application and tried to use the same library that i wrote before and so i got the error.
The problem is that the NuGetPackage in myLib (old version of Owin.Hosting) is not compatible with the new package version which is released 12 days ago . The new changes do not support WebApplication (from old version). It is called now WebApp.

Error running a simple MDB application

I am trying to run the following program.I am using glassfish server 3.1.2 to enable this MDB to run.Then too I am unanble to run it.
package com.mdb;
import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.Connection;
import javax.jms.Session;
import javax.jms.QueueBrowser;
import javax.jms.Message;
import javax.jms.JMSException;
import javax.annotation.Resource;
import java.util.Enumeration;
import javax.ejb.Stateless;
/**
* The MessageBrowser class inspects a queue and displays the messages it
* holds.
*/
#Stateless
public class MessageClient {
#Resource(mappedName = "jms/ConnectionFactory")
private static ConnectionFactory connectionFactory;
#Resource(mappedName = "jms/Queue")
private static Queue queue;
/**
* Main method.
*
* #param args the queue used by the example
*/
public static void main(String[] args) {
Connection connection = null;
try {
System.out.println("1");
connection = connectionFactory.createConnection();
System.out.println("2");
Session session = connection.createSession(
false,
Session.AUTO_ACKNOWLEDGE);
QueueBrowser browser = session.createBrowser(queue);
Enumeration msgs = browser.getEnumeration();
if (!msgs.hasMoreElements()) {
System.out.println("No messages in queue");
} else {
while (msgs.hasMoreElements()) {
Message tempMsg = (Message) msgs.nextElement();
System.out.println("Message: " + tempMsg);
}
}
} catch (JMSException e) {
System.err.println("Exception occurred: " + e.toString());
} finally {
if (connection != null) {
try {
connection.close();
} catch (JMSException e) {
}
}
}
}
}
The problem is I get the follwing exsception upon runing it.
Exception in thread "main" java.lang.NullPointerException
at com.mdb.MessageClient.main(MessageClient.java:35)
What may be the problem here?
What you have build is not a MDB. It's a stateless session bean that browses a queue.
A MDB has the #MessageDriven annotation. It's invoked whenever a message comes in.
Apart from that, you might want to use the "lookup" attribute instead of the "mappedName" one. The latter is from an ancient time when people weren't sure yet about anything, and needed a temporary hack to make things magically work.
Your usage of static fields and the static main method inside a stateless bean make no sense at all. If you're accessing your bean via that main method you're not using the bean at all and you're just calling an isolated global-like method. If anything, this might be the source of your NPE.
The fix isn't really simple. You're seemingly completely confused between Java EE and Java SE, and between instances and static methods.

Dependency Injection Query

I'm starting a web application that contains the following projects:
Booking.Web
Booking.Services
Booking.DataObjects
Booking.Data
I'm using the repository pattern in my data project only. All services will be the same, no matter what happens. However, if a customer wants to use Access, it will use a different data repository than if the customer wants to use SQL Server.
I have StructureMap, and want to be able to do the following:
Web project is unaffected. It's a web forms application that will only know about the services project and the dataobjects project.
When a service is called, it will use StructureMap (by looking up the bootstrapper.cs file) to see which data repository to use.
An example of a services class is the error logging class:
public class ErrorLog : IErrorLog
{
ILogging logger;
public ErrorLog()
{
}
public ErrorLog(ILogging logger)
{
this.logger = logger;
}
public void AddToLog(string errorMessage)
{
try
{
AddToDatabaseLog(errorMessage);
}
catch (Exception ex)
{
AddToFileLog(ex.Message);
}
finally
{
AddToFileLog(errorMessage);
}
}
private void AddToDatabaseLog(string errorMessage)
{
ErrorObject error =
new ErrorObject
{
ErrorDateTime = DateTime.Now,
ErrorMessage = errorMessage
};
logger.Insert(error);
}
private void AddToFileLog(string errorMessage)
{
// TODO: Take this value from the web.config instead of hard coding it
TextWriter writer = new StreamWriter(#"E:\Work\Booking\Booking\Booking.Web\Logs\ErrorLog.txt", true);
writer.WriteLine(DateTime.Now.ToString() + " ---------- " + errorMessage);
writer.Close();
}
}
I want to be able to call this service from my web project, without defining which repository to use for the data access. My boostrapper.cs file in the services project is defined as:
public class Bootstrapper
{
public static void ConfigureStructureMap()
{
ObjectFactory.Initialize(x =>
{
x.AddRegistry(new ServiceRegistry());
}
);
}
public class ServiceRegistry : Registry
{
protected override void configure()
{
ForRequestedType<IErrorLog>().TheDefaultIsConcreteType<Booking.Services.Logging.ErrorLog>();
ForRequestedType<ILogging>().TheDefaultIsConcreteType<SqlServerLoggingProvider>();
}
}
}
What else do I need to get this to work? When I defined a test, the ILogger object was null.
Perhaps some details on how you are calling this code from a test would be useful.
My understanding is that you need to ensure that the ConfigureStructureMap call has been made early in the applications life (e.g. in the Global.asax in a web project).
After that you would be calling for instances of IErrorLog using something like:
IErrorLog log = StructureMap.ObjectFactory.GetNamedInstance<IErrorLog>();

Resources