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.
Related
One operator deleted Data Dictionary and restarted Alfresco 3.4.12 Enterprise Edition. The context /alfresco doesn't start with the following exception:
17:43:11,100 INFO [STDOUT] 17:43:11,097 ERROR [web.context.ContextLoader] Context initialization failed
org.alfresco.error.AlfrescoRuntimeException: 08050000 Failed to find 'app:dictionary' node
at org.alfresco.repo.action.scheduled.ScheduledPersistedActionServiceImpl.locatePersistanceFolder(ScheduledPersistedActionServiceImpl.java:132)
Looking at the source code in org.alfresco.repo.action.scheduled.ScheduledPersistedActionServiceImpl.java, the path is hardwired.
Then we followed the tip from https://community.alfresco.com/thread/202859-error-failed-to-find-appdictionary-node, editing bootstrap-context.xml, comment out the class.
After the change the error went over, now the RenditionService couldn't start.
We're looking for a way to recover the deleted node, since we can obtain the nodeid from the database. So we created a small class and invoke it through spring in bootstrap-context.xml, but it's failing due to permissions. Could you take a look at the code and tell us what's wrong. The code is:
package com.impulseit.test;
import javax.transaction.UserTransaction;
import org.alfresco.repo.node.archive.NodeArchiveService;
import org.alfresco.repo.node.archive.RestoreNodeReport;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.NodeRef;
public class RestoreNode {
private NodeArchiveService nodeArchiveService;
private ServiceRegistry serviceRegistry;
private String nodeName ="archive://SpacesStore/adfc0cfe-e20b-467f-ad71-253aea8f9ac9";
public void setNodeArchiveService(NodeArchiveService value)
{
this.nodeArchiveService = value;
}
public void setServiceRegistry(ServiceRegistry value)
{
this.serviceRegistry = value;
}
public void doRestore() {
RunAsWork<Void> runAsWork = new RunAsWork<Void>()
{
public Void doWork() throws Exception
{
NodeRef nodeRef = new NodeRef(nodeName);
//RestoreNodeReport restoreNodeReport =
UserTransaction trx_A = serviceRegistry.getTransactionService().getUserTransaction();
trx_A.begin();
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
RestoreNodeReport restored = nodeArchiveService.restoreArchivedNode(nodeRef);
trx_A.commit();
return null;
}
};
AuthenticationUtil.runAs(runAsWork,AuthenticationUtil.getSystemUserName());
}
public RestoreNode() {
}
}
The exception is:
19:31:21,747 User:admin ERROR [node.archive.NodeArchiveServiceImpl] An unhandled exception stopped the restore
java.lang.NullPointerException
at org.alfresco.repo.security.permissions.impl.model.PermissionModel.getPermissionReference(PermissionModel.java:1315)
at org.alfresco.repo.security.permissions.impl.PermissionServiceImpl.getPermissionReference(PermissionServiceImpl.java:956)
at org.alfresco.repo.security.permissions.impl.PermissionServiceImpl.hasPermission(PermissionServiceImpl.java:976)
Thank you in advance.
Luis
In my JavaFX application, I want to show an error dialog and exit the app whenever some unexpected exception occurs. So in my main-method I have set up a default uncaught exception handler before launching the app:
setDefaultUncaughtExceptionHandler((thread, cause) -> {
try {
cause.printStackTrace();
final Runnable showDialog = () -> {
// create dialog and show
};
if (Platform.isFxApplicationThread()) {
showDialog.run();
} else {
runAndWait(showDialog);
}
} catch (Throwable t) {
// ???
} finally {
System.exit(-1);
}
});
launch(MyApp.class);
Explanation: When the uncaught exception handler is executed on the JavaFX Application Thread (FXAT), I just run the code for showing the dialog. This of course doesn't work when the exception handler is not invoked by the FXAT. In this case, I have to push the code onto the FXAT. But I can't use Platform.runLater because then my app would exit before the dialog is shown. So, I made that custom method runAndWait which internally pushes the runnable via Platform.runLater, but waits until the execution of the runnable (with some countdown latch mechanism).
Now the problem with this: When an exception occurs in my start() method then my app gets stuck. Because it tries to wait until the execution of the dialog showing, but the FXAT never does this execution. I guess this is because when the start() method fails with an exception, the FXAT is just dead? I'm not sure whether this is a special case for the start() method or whether this will happen in any situation when an exception is thrown and not caught within code that is executed by the FXAT.
In Swing as I know the EDT is a complex architecture consisting of several threads. It wasn't the case that when some execution on the EDT failed that the entire Swing broke down. But here this is what seems to happen?
So what can I do here? How can I show to the user that the application cannot start?
Well....
I have a solution but I don't particularly recommend it. By default, Application.launch() will catch the exception thrown by the start method, exit the FX Platform, and then rethrow the exception. Since the FX Application Thread has shut down when your default uncaught exception handler executes, waiting for something to happen on the FX Application Thread just blocks indefinitely.
The exception to this is when the FX Application is running in web start. The way that the launcher checks for this is to check for the presence of a security manager. So a (really, really ugly) workaround is to install a security manager so that it looks like you are running in web start mode. This line will install a permissive security manager:
System.setSecurityManager(new SecurityManager(){
#Override
public void checkPermission(Permission perm) {}
});
Here's a SSCCE:
import java.lang.Thread.UncaughtExceptionHandler;
import java.security.Permission;
import java.util.concurrent.FutureTask;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
public class ShowDialogOnException {
public static final UncaughtExceptionHandler ALERT_EXCEPTION_HANDLER = (thread, cause) -> {
try {
cause.printStackTrace();
final Runnable showDialog = () -> {
Alert alert = new Alert(AlertType.ERROR);
alert.setContentText("An unknown error occurred");
alert.showAndWait();
};
if (Platform.isFxApplicationThread()) {
showDialog.run();
} else {
FutureTask<Void> showDialogTask = new FutureTask<Void>(showDialog, null);
Platform.runLater(showDialogTask);
showDialogTask.get();
}
} catch (Throwable t) {
t.printStackTrace();
} finally {
System.exit(-1);
}
};
public static void main(String[] args) {
System.setSecurityManager(new SecurityManager(){
#Override
public void checkPermission(Permission perm) {}
});
Thread.setDefaultUncaughtExceptionHandler(ALERT_EXCEPTION_HANDLER);
Application.launch(App.class, args);
}
}
and a test app:
import javafx.application.Application;
import javafx.stage.Stage;
public class App extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
throw new Exception("An exception");
}
#Override
public void stop() {
System.out.println("Stop");
}
}
As I said, this is really something of a big hack, and I don't really recommend this unless you have no other option.
I have an EJB to calculate sth. with increasing precision as long as the calculation runs.
So one async function starts the calculation and one async should stop it. But Running on Glassfish 3.1.2 calling stopCalculating() does not create a new Thread but waits until startCalculating() finishes, what obviously never happens.
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.AsyncResult;
import javax.ejb.Asynchronous;
import javax.ejb.Singleton;
#Singleton
public class Calculator {
private boolean calculating = false;
private String result = "Empty";
#Asynchronous
public void startCalculating() {
calculating = true;
Logger.getGlobal().log(Level.INFO, "Starting!");
calculate();
}
private void calculate() {
result = "";
while(calculating) {
/*Calculate and update result*/
Logger.getGlobal().log(Level.INFO, "Calculate...");
}
}
#Asynchronous
public Future<String> stopCalculating() {
Logger.getGlobal().log(Level.INFO, "Stopping!");
calculating = false;
return new AsyncResult<String>(result);
}
}
How can I get Glassfish to run stopCalculating() in an other Thread?
I think it's because by default Singleton EJB has #Lock(WRITE) access.
You're using local calls instead of going through EJB proxy so calculate() invoked from startCalculating(-) is a part of the whole startCalculating(-) invocation (so has #Local(WRITE) as well).
I'd try adding #Lock(READ) to your calculate() method and change the local call to business call or just set #Lock(READ) for your EJB and give it a shot.
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.
using ejb 3.1, servlet 3.0 (glassfish server v3)
Scenario:
I have MDB that listen to jms messages and give processing to some other session bean (Stateless).
Servelet injecting jms resource.
Question 1: Why servlet can`t inject jms resources when they use static declaration ?
#Resource(mappedName = "jms/Tarturus")
private static ConnectionFactory connectionFactory;
#Resource(mappedName = "jms/StyxMDB")
private static Queue queue;
private Connection connection;
and
#PostConstruct
public void postConstruct() {
try {
connection = connectionFactory.createConnection();
} catch (JMSException e) {
e.printStackTrace();
}
}
#PreDestroy
public void preDestroy() {
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
The error that I get is :
[#|2010-05-03T15:18:17.118+0300|WARNING|glassfish3.0|javax.enterprise.system.container.web.com.sun.enterprise.web|_ThreadID=35;_ThreadName=Thread-1;|StandardWrapperValve[WorkerServlet]:
PWC1382: Allocate exception for
servlet WorkerServlet
com.sun.enterprise.container.common.spi.util.InjectionException:
Error creating managed object for
class
ua.co.rufous.server.services.WorkerServiceImpl
at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.createManagedObject(InjectionManagerImpl.java:312)
at
com.sun.enterprise.web.WebContainer.createServletInstance(WebContainer.java:709)
at
com.sun.enterprise.web.WebModule.createServletInstance(WebModule.java:1937)
at
org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1252)
Caused by:
com.sun.enterprise.container.common.spi.util.InjectionException:
Exception attempting to inject
Unresolved Message-Destination-Ref
ua.co.rufous.server.services.WorkerServiceImpl/queue#java.lang.String#null
into class
ua.co.rufous.server.services.WorkerServiceImpl
at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:614) at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.inject(InjectionManagerImpl.java:384)
at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.injectInstance(InjectionManagerImpl.java:141)
at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.injectInstance(InjectionManagerImpl.java:127)
at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl.createManagedObject(InjectionManagerImpl.java:306)
... 27 more Caused by:
com.sun.enterprise.container.common.spi.util.InjectionException:
Illegal use of static field private
static javax.jms.Queue
ua.co.rufous.server.services.WorkerServiceImpl.queue
on class that only supports
instance-based injection at
com.sun.enterprise.container.common.impl.util.InjectionManagerImpl._inject(InjectionManagerImpl.java:532) ... 31 more |#]
my MDB :
/**
* asadmin commands
* asadmin create-jms-resource --restype javax.jms.ConnectionFactory jms/Tarturus
* asadmin create-jms-resource --restype javax.jms.Queue jms/StyxMDB
* asadmin list-jms-resources
*/
#MessageDriven(mappedName = "jms/StyxMDB", activationConfig =
{
#ActivationConfigProperty(propertyName = "connectionFactoryJndiName", propertyValue = "jms/Tarturus"),
#ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
#ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
public class StyxMDB implements MessageListener {
#EJB
private ActivationProcessingLocal aProcessing;
public StyxMDB() {
}
public void onMessage(Message message) {
try {
TextMessage msg = (TextMessage) message;
String hash = msg.getText();
GluttonyLogger.getInstance().writeInfoLog("geted jms message hash = " + hash);
} catch (JMSException e) {
}
}
}
everything work good without static declaration:
#Resource(mappedName = "jms/Tarturus")
private ConnectionFactory connectionFactory;
#Resource(mappedName = "jms/StyxMDB")
private Queue queue;
private Connection connection;
Question 2:
what is the best practice for working with MDB : processing full request in onMessage() or calling another bean(Stateless bean in my case) in onMessage() method that would process it.
Processing including few calls to soap services, so the full processing time could be for a 3 seconds.
Thank you.
Answers:
1. You cannot inject a resource into a static field. Injection into member fields occurs during object construction, static fields are not part of the object (only part of the class). In addition EJBs and servlets are threaded objects so this could possibly be dangerous to do.
2. If splitting the processing up into multiple EJB(s) makes sense do it that way, otherwise processing in onMessage() is perfectly valid.
One additional suggestion that I can give, is that you should take a look at CDI which is a new addition to the EE 6 specification and provides rich dependency injection.
Are you using an MDB to perform asynchronous operations, Servlet 3.0 has some neat asynchronous capabilities. I suggest you watch the entire presentation if you are not familiar with Servlet 3.0.