Local SQLite connection on JDeveloper - sqlite

I'm completely new to ADF Mobile and have previously made a connection to and SQLite DB with NetBeans. I'm replicating the code, and I'm getting an Import java.sql.DriverManager not found error (in bold).
package mobile;
import java.sql.Connection;
**import java.sql.DriverManager;**
import java.sql.*;
public class Connect {
public Connect() {
super();
}
public class JavaConnect {
static Connection conn = null;
static ResultSet rs = null;
static PreparedStatement pst = null;
public static Connection DBConnect() {
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:AlternativeIdentification.sqlite");
System.out.println("Connection established");
return conn;
} catch (Exception ex) {
System.out.println("Error: " + ex);
return null;
}
}

Download https://code.google.com/p/sqlite-jdbc/. Then in your JDeveloper go to Tools>ManageLibraries and create a new library. Check the 'DeployedByDefault' checkbox there and add the JAR in the library (>addEntry). Then go to your Project, go to ProjectProperties and then to Libraries and Classpath and click on Add Library to add your new library to your project. Rebuild your project or restart JDeveloper in the worst case and you should be fine.

Related

No COM ports identified with usb4java

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)
}
}

NoInitialContextException in simple EJB Project on Wildfly 8

I am trying to write a client for a simple EJB Project that I have deployed locally on my Wildfly 8 running in Eclipse.
My Interface:
package com.jwt.ejb.business;
import javax.ejb.Remote;
#Remote
public interface Hello {
public String sayHello();
}
My Implementation:
package com.jwt.ejb.businesslogic;
import javax.ejb.Stateless;
import com.jwt.ejb.business.Hello;
#Stateless
public class HelloBean implements Hello {
public HelloBean() {
}
public String sayHello() {
return "Hello Boss Welcome to EJB";
}
}
My client:
package com.jwt.ejb.test;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.jwt.ejb.business.Hello;
import com.jwt.ejb.businesslogic.HelloBean;
public class Client {
public static void main(String[] args) {
Hello bean = doLookup();
if (bean != null)
System.out.println(bean.sayHello());
}
private static Hello doLookup() {
Context context = null;
Hello bean = null;
try {
final Hashtable jndiProperties = new Hashtable();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
context = new InitialContext(jndiProperties);
bean = (Hello) context.lookup(getLookupString());
} catch (NamingException e) {
e.printStackTrace();
}
return bean;
}
private static String getLookupString() throws NamingException {
final String appName = "";
final String moduleName = "EJBTest";
final String distinctName = "";
final String beanName = HelloBean.class.getSimpleName();
final String viewClassName = Hello.class.getName();
return "ejb:" + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + viewClassName;
}
}
When I run it, I get this Exception:
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.lookup(Unknown Source)
at com.jwt.ejb.test.Client.doLookup(Client.java:26)
at com.jwt.ejb.test.Client.main(Client.java:15)
Exception in thread "main" java.lang.NullPointerException
at com.jwt.ejb.test.Client.main(Client.java:16)
The official documentation does it like this too:
https://docs.jboss.org/author/display/AS71/EJB+invocations+from+a+remote+client+using+JNDI
Where is the problem ?
I came accross posts talking about boss-ejb-client.properties, but I am not sure what to put in it. As I understood it, I could either have this properties file, or declare the porperties programmatically, like I did.
Besides the fact that you are using Wildfly 8 and referencing JBoss AS 7.1's documentation, you're missing the InitialContextFactory on your JNDI properties.
Wildfly's documentation on EJB invocations via JNDI is here. Therefore you should do the following:
void doBeanLookup() {
Properties jndiProperties = new Properties();
jndiProperties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
jndiProperties.put(Context.PROVIDER_URL, "http-remoting://localhost:8080");
// This is an important property to set if you want to do EJB invocations via the remote-naming project
jndiProps.put("jboss.naming.client.ejb.context", true);
// create a context passing these properties
Context ctx = new InitialContext(jndiProps);
// lookup the bean Hello
Hello bean = (Hello) ctx.lookup(getLookupString());
}
In your pom.xml you should have the following:
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-ejb-client-bom</artifactId>
<version>8.0.0.Final</version>
<type>pom</type>
</dependency>
If you want to use the http-remoting protocol, on your getLookupString method, you should remove the ejb: and have present that
http-remoting client assumes JNDI names in remote lookups are relative to java:jboss/exported namespace, a lookup of an absolute JNDI name will fail.
Further information can be found on Wildfly 8 Remote JNDI Reference Update Draft.

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.

servlet has to be reloaded everyday

I have created a servlet to access a database and giving response to a BB application...it was running fine during development...but after loading it on a tomcat server 6.0 after goining live the servlet has to be reloaded every morning on the tomcat server....after that it works fine during the whole day..but the next morning when i request something it gives a blank page as response and my server admin tells the servlet has to be reloaded ...
other application hosted on the server are working fine and do not need a restart...
what might be the problem....
adding the code ..if it helps
package com.ams.servlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import com.cms.dbaccess.DataAccess;
import com.cms.utils.ApplicationConstants;
import com.cms.utils.ApplicationHelper;
import java.sql.ResultSet;
public class BBRequestProcessorServlet extends HttpServlet {
/**
*
*/String userString;
private static final long serialVersionUID = 1L;
String jsonString = "";
ResultSet rs = null;
Connection connection = null;
Statement statement=null;
public enum db_name
{
//Test
resource_management_db,osms_inventory_db;
}
public void init(ServletConfig config)throws ServletException
{
super.init(config);
System.out.println("Inside init");
}
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException
{
try{
connection = DataAccess.connectToDatabase("xxx", connection);
statement = DataAccess.createStatement(connection);
statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = statement.executeQuery("query is here");
}
catch(SQLException e)
{
e.printStackTrace();
}
String db =request.getParameter("db");
System.out.println("DATABASE NAME :"+ db);
if(db.equalsIgnoreCase("xxx")){
//Call to populate JSONArray with the fetch ResultSet data
jsonString = ApplicationHelper.populateJSONArray(rs);
}
response.setContentType(ApplicationConstants.JSON_CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.print(jsonString);
out.flush();
out.close();
System.out.println("json object sent");
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
the only errors i could find was
Jul 20, 2012 9:57:24 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(/usr/local/tomcat/apache-tomcat-6.0.20/webapps/MobileServlet /WEB-INF/lib/servlet-api.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
The culprit is most likely the way how you handle external DB resources like the Connection. This problem can happen when you keep a DB Connection open all the time without closing it. When a DB Connection is been opened for a too long time, then the DB will timeout and reclaim it. This is most likely what was happening overnight.
You should redesign your DataAccess and BBRequestProcessorServlet that way so that you are nowhere keeping hold of Connection, Statement and ResultSet as an instance variable, or worse, a static variable of the class. The Connection should be created in the very same scope as where you're executing the SQL query/queries and it should be closed in the finally block of the very same try block as where you've created it.
By the way your jsonString should absolutely also not be declared as an instance variable of the servlet, it's not threadsafe this way.
See also:
Is it safe to use a static java.sql.Connection instance in a multithreaded system?
How do servlets work? Instantiation, sessions, shared variables and multithreading
As to the error which you're seeing in the log, you should definitely remove the offending JAR. See also How do I import the javax.servlet API in my Eclipse project?
I am guessing and will be more clear after seeing your logs.
Its seems like you have putted your servlet-api.jar in the WEB-INF lib but its already in tomcat's lib.

How do I use a custom realm with GlassFish 3.1?

I would like to use a custom realm with glassfish 3.1
I took the two file from this topic to try. Custom Glassfish Security Realm does not work (unable to find LoginModule)
The CustomRealm.java
package com.company.security.realm;
import com.sun.appserv.security.AppservRealm;
import com.sun.enterprise.security.auth.realm.BadRealmException;
import com.sun.enterprise.security.auth.realm.InvalidOperationException;
import com.sun.enterprise.security.auth.realm.NoSuchRealmException;
import com.sun.enterprise.security.auth.realm.NoSuchUserException;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;
public class CustomRealm extends AppservRealm
{
Vector<String> groups = new Vector<String>();
private String jaasCtxName;
private String startWith;
#Override
public void init(Properties properties)
throws BadRealmException, NoSuchRealmException {
jaasCtxName = properties.getProperty("jaas-context", "customRealm");
startWith = properties.getProperty("startWith", "z");
groups.add("dummy");
}
#Override
public String getAuthType()
{
return "Custom Realm";
}
public String[] authenticate(String username, char[] password)
{
// if (isValidLogin(username, password))
return (String[]) groups.toArray();
}
#Override
public Enumeration getGroupNames(String username)
throws InvalidOperationException, NoSuchUserException
{
return groups.elements();
}
#Override
public String getJAASContext()
{
return jaasCtxName;
}
public String getStartWith()
{
return startWith;
}
}
And the custom login module
package com.company.security.realm;
import com.sun.appserv.security.AppservPasswordLoginModule;
import com.sun.enterprise.security.auth.login.common.LoginException;
import java.util.Set;
import org.glassfish.security.common.PrincipalImpl;
public class CustomLoginModule extends AppservPasswordLoginModule
{
#Override
protected void authenticateUser() throws LoginException
{
_logger.info("CustomRealm : authenticateUser for " + _username);
final CustomRealm realm = (CustomRealm)_currentRealm;
if ( (_username == null) || (_username.length() == 0) || !_username.startsWith(realm.getStartWith()))
throw new LoginException("Invalid credentials");
String[] grpList = realm.authenticate(_username, getPasswordChar());
if (grpList == null) {
throw new LoginException("User not in groups");
}
_logger.info("CustomRealm : authenticateUser for " + _username);
Set principals = _subject.getPrincipals();
principals.add(new PrincipalImpl(_username));
this.commitUserAuthentication(grpList);
}
}
I added as well the module to the conf file
customRealm {
com.company.security.realm.CustomLoginModule required;
};
And I copy my 2 .class in the glassfish3/glassfish/domains/domain1/lib/classes/
as well as glassfish3/glassfish/lib
Everytime I want to create a new realm I have got the same error.
./asadmin --port 4949 create-auth-realm --classname com.company.security.realm.CustomRealm --property jaas-context=customRealm:startWith=a customRealm
remote failure: Creation of Authrealm customRealm failed. com.sun.enterprise.security.auth.realm.BadRealmException: java.lang.ClassNotFoundException: com.company.security.realm.CustomRealm not found by org.glassfish.security [101]
com.sun.enterprise.security.auth.realm.BadRealmException: java.lang.ClassNotFoundException: com.company.security.realm.CustomRealm not found by org.glassfish.security [101]
Command create-auth-realm failed.
I think i dont really understand how to add in the proper way my two files to glassfish.
This two files are created and compile from eclipse. I create a java project suctom login.
Someone can help ?
Thx a lot in advance,
loic
Did you package it as an OSGi module (see the answer in the post you referenced)? If so, don't copy the jar file into $GF_HOME/lib or anything, instead deploy it as an OSGi module:
asadmin deploy --type osgi /path/to/CustomRealm.jar
Then add the login.conf settings. To be on the safe side, I'd restart GF (asadmin restart-domain), then you can create the realm with the command you have there.

Resources