Open a file at #Timeout of a timerservice - glassfish-3

Every time I try to open a file at the #Timeout, Java returns Null Pointer Exception
#Singleton
public class EngineTrans {
#Resource
private TimerService timerService;
public void createProgrammaticalTimer() {
ScheduleExpression everyTenSeconds = new ScheduleExpression().second("*/15").minute("*").hour("4-20");
timerService.createCalendarTimer(everyTenSeconds, new TimerConfig(
"passed message " + new Date(), false));
}
#Timeout
public void handleTimer() {
System.out.println("timer received - contained message is: " + new Date());
File xmlFile = new File(FacesContext.getCurrentInstance().getExternalContext().getRealPath(""));
}
}
Any ideas?

There is no JSF context within an #Timeout method. Perform the getRealPath call in the createProgrammaticalTimer method, and then pass it to the #Timeout method via the first parameter of the TimerConfig constructor (the "info" parameter). If necessary, create an inner class to hold all the data you need to pass to the #Timeout method:
#Singleton
public class EngineTrans {
#Resource
private TimerService timerService;
private static class TimeoutData {
private final Date date = new Date();
private final String resourcePath;
...
}
public void createProgrammaticalTimer() {
...
String resourcePath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("...");
TimeoutData timeoutData = new TimeoutData(resourcePath);
timerService.createCalendarTimer(everyTenSeconds, new TimerConfig(timeoutData, false));
}
#Timeout
public void handleTimer(Timer timer) {
TimeoutData timeoutData = (TimeoutData)timer.getInfo();
...
}
}

Related

Null data Passing Variable from Controller A to Controller B

Hello I am Trying to pass Variable data from database from one Controller to another, but I Have one problem, when I am passing the data to the controller A to Controller B, appear a Null value, the jerarchy between Scenes is this:
LoginController->AdminController->UserController
in the LoginController to Access AdminController and Pass the Value i do this:
public String getRoladmin() {
return roladmin;
}
public void setRoladmin(String roladmin) {
this.roladmin = roladmin;
}
public String roladmin="";
I Capture the Variable roladmin in this portion of my code like this:
while(rs.next()) {
comparauser=rs.getString("NOMBREUSUARIO");
comparapass=rs.getString("PASS");
miadmin=rs.getString("NOMBRE_ADMIN");
roladmin=rs.getString("ROL_ADMIN");
}
to access the Stage I validate if the user and pass are correct like this:
----rest of code--- if(comparauser.equals(fusuario.getText().toString())&&comparapass.equals(fcontrasena.getText().toString().trim())) {
try {
Stage administrador=new Stage();
FXMLLoader carga = new FXMLLoader(getClass().getResource("Admin.fxml"));
Parent StackPane = (Parent)carga.load();
Scene scene = new Scene(StackPane);
AdminScreenController loadl = carga.<AdminScreenController>getController();
/*loadl.UserScreen.setText("Bienvenido"+" "+fusuario.getText().toString());*/
loadl.UserScreen.setText("Bienvenido"+" "+miadmin);
/* String r=loadl.UserScreen.getText().toString();*/
-----in this part I call the LoginController and pass the variable Roladmin------
----begin of call--
String h=LoginController.this.roladmin;
LoginController.this.setRoladmin(h);
String r=LoginController.this.getRoladmin();
loadl.setCapdata(r);
-----end of call-----
if(!r.equals("ADMINISTRADOR")) {
loadl.btnimg5.setDisable(true);
loadl.btnimg5.setStyle("-fx-opacity:0.65;");
}
else {
loadl.btnimg5.setDisable(false);
}
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
administrador.setScene(scene);
administrador.setTitle("AdminScreen");
Stage login=(Stage)fusuario.getScene().getWindow();
login.hide();
administrador.show();
}catch(Exception e) {
Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, e);
}
}
---rest of code---
now i Pass that variable to the AdminController like this
in AdminController i have this:
public String capdata;
public String h;
public String getCapdata() {
return capdata;
}
public String setCapdata(String data) {
return this.capdata = data;
}
this is the code i have to load UserController Stage:
public void UserView() throws IOException {
Stage userstage = new Stage();
FXMLLoader cargauser =new FXMLLoader(getClass().getResource("UsuarioScreen.fxml"));
Parent StackPane = (Parent)cargauser.load();
UserController cargatodouser = cargauser.<UserController>getController();
String pasadato=UserScreen.getText().toString();
cargatodouser.iduser.setText(pasadato);
---begin of call to pass the variable---
h=AdminScreenController.this.getCapdata();
---end of call---
/*String r=cargatodouser.iduser.getText().toString();*/
Scene scene = new Scene(StackPane);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
userstage.setScene(scene);
userstage.setTitle("QuoraApp");
Stage AdminScreen=(Stage)btnimg1.getScene().getWindow();
AdminScreen.hide();
userstage.show();
}
now when i am passing the variable to the UserController Class i have a null value I am doing this:
In UserController class i have this to go back AdminController:
public String capturau;
public String getCapturau() {
return capturau;
}
public String setCapturau(String capturau) {
return this.capturau = capturau;
}
public void inicio() throws IOException {
Stage administrador=new Stage();
FXMLLoader carga = new FXMLLoader(getClass().getResource("Admin.fxml"));
Parent StackPane =(Parent) carga.load();
AdminScreenController loadl = carga.<AdminScreenController>getController();
String pasadato=iduser.getText().toString();
loadl.UserScreen.setText(pasadato);
/*Captura.setText(loadl.getCapdata());
String captura=Captura.getText().toString();
System.out.println(captura);*/
UserController.this.setCapturau(loadl.getCapdata());
String gg=UserController.this.getCapturau();
System.out.println(gg);
}
what i am doing wrong? a little help here please.
You need to look into the concept of static variables
Here is a static variable I declare on one Controller and use and another Controller
A BIG word of caution about using static variables or Global Variables
What ever you put in a static variable it holds that value till you clear it or change it
static Integer strID;
Here is the use of the static variable strID in the other Controller Class
Notice it needs to be imported to the new Controller
import static diary.ChildTableViewController.strID;
private void ReadDetailView() throws SQLException{
stmnt = conn.createStatement();
///String sql = "SELECT * FROM Child WHERE CID = "+strID;
///ResultSet rs = stmnt.executeQuery(sql);
ResultSet rs = stmnt.executeQuery("SELECT * FROM Child WHERE CID = "+strID);
Welcome to SO

How to use Jackson to deserialise list in java?

My Java Class is
public class User {
private List<UserInfo> userInfoList;
public class UserInfo {
private String id;
}
}
Let's assume it has getter, setter method.
json is
{"userInfoList" : [{"id":"a", "id":"b"}]}
I tried to deserialize it like below.
objectMapper.readValue(json, User.class);
But it throws error.
Can not construct instance of User$UserInfoList: no suitable constructor found
How to deserialize it?
I think you should make UserInfo static. Jackson cannot construct the UserInfo class.
I tried with that change and it works for me :
public class User {
private List<UserInfo> userInfoList;
public static class UserInfo {
private String id;
public UserInfo() {
super();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
public List<UserInfo> getUserInfoList() {
return userInfoList;
}
public void setUserInfoList(List<UserInfo> userInfoList) {
this.userInfoList = userInfoList;
}
}
And :
public class App {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
User.UserInfo ui1 = new User.UserInfo();
ui1.setId("a");
User.UserInfo ui2 = new User.UserInfo();
ui2.setId("b");
List<User.UserInfo> userInfoList = new ArrayList<User.UserInfo>();
userInfoList.add(ui1);
userInfoList.add(ui2);
User user = new User();
user.setUserInfoList(userInfoList);
System.out.println(mapper.writeValueAsString(user));
user = mapper.readValue(mapper.writeValueAsString(user), User.class);
}
}

Get nullPoint when using NamedParameterJdbcTemplate

Depending on project's requirement, we want to change from JdbcTemplate into NamedParameterJdbcTemplate in database handling. But I got null point error when I test my coding. I'm sure the error has occurred because of my configuration, but I could not resolve it.
Config
#Value("${spring.datasource.driver-class-name}")
protected String driver;
#Value("${spring.datasource.url}")
protected String url;
#Value("${spring.datasource.username}")
protected String user;
#Value("${spring.datasource.password}")
protected String pass;
#Bean
public DataSource dataSource(){
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(pass);
dataSource.setTestOnBorrow(true);
dataSource.setTestOnReturn(true);
dataSource.setTestWhileIdle(true);
return dataSource;
}
#Bean
public JdbcTemplate jdbcTemplate(){
return new JdbcTemplate(dataSource());
}
#Bean
public NamedParameterJdbcTemplate namedParameterJdbcTemplate(){
return new NamedParameterJdbcTemplate(dataSource);
}
DaoImpl
#Repository
public class DAOImpl implements DAO {
#Autowired
private NamedParameterJdbcTemplate jdbcTemplate;
#Override
public List<Type> findAllType() {
String sql = "select * from type";
RowMapper<Type> rm = new TypeRowMapper();
List<Type> list = jdbcTemplate.query(sql, rm);
return list;
}
}
Test
public class Test {
#Autowired
protected DAOImpl dao;
public static void main(String[] args) {
List<Type> list = new ArrayList<Type>();
Test test = new Test();
System.out.println(test.dao);
list = test.dao.findAllType();
for(Type type : list){
System.out.println(type.getName());
}
}
}
Stacktrace
null
Exception in thread "main" java.lang.NullPointerException
at com.example.dao.Test.main(Test.java:18)

Is there a way to make Spring Thymeleaf process a string template?

I would like to write something like :
#Autowired
private SpringTemplateEngine engine;
....
// Thymeleaf Context
WebContext thymeleafContext = new WebContext(request, response, request.getServletContext(), locale);
// cached html of a thymeleaf template file
String cachedHtml=....
// process the cached html
String html=engine.process(cachedHtml, thymeleafContext);
By default, the [process] method can't do that. I can understand from the docs that I need a special Template Resolver :
In order to execute templates, the process(String, IContext) method will be used:
final String result = templateEngine.process("mytemplate", ctx);
The "mytemplate" String argument is the template name, and it will relate to the physical/logical location of the template itself in a way configured at the template resolver/s.
Does anyone know how to solve my problem ?
The goal is to cache the Thymeleaf templates (files) in strings and then process theses strings rather than the files.
The solution we ended up using consisted of a new IResourceResolver with a custom Context rather than a custom TemplateResolver. We chose this because we still wanted to use classpath scanning in most cases, but occasionally had dynamic content.
The following shows how we did it:
public class StringAndClassLoaderResourceResolver implements IResourceResolver {
public StringAndClassLoaderResourceResolver() {
super();
}
public String getName() {
return getClass().getName().toUpperCase();
}
public InputStream getResourceAsStream(final TemplateProcessingParameters params, final String resourceName) {
Validate.notNull(resourceName, "Resource name cannot be null");
if( StringContext.class.isAssignableFrom( params.getContext().getClass() ) ){
String content = ((StringContext)params.getContext()).getContent();
return IOUtils.toInputStream(content);
}
return ClassLoaderUtils.getClassLoader(ClassLoaderResourceResolver.class).getResourceAsStream(resourceName);
}
public static class StringContext extends Context{
private final String content;
public StringContext(String content) {
this.content = content;
}
public StringContext(String content, Locale locale) {
super(locale);
this.content = content;
}
public StringContext(String content, Locale locale, Map<String, ?> variables) {
super(locale, variables);
this.content = content;
}
public String getContent() {
return content;
}
}
Test Case
public class StringAndClassLoaderResourceResolverTest {
private static SpringTemplateEngine templateEngine;
#BeforeClass
public static void setup(){
TemplateResolver resolver = new TemplateResolver();
resolver.setResourceResolver(new StringAndClassLoaderResourceResolver());
resolver.setPrefix("mail/"); // src/test/resources/mail
resolver.setSuffix(".html");
resolver.setTemplateMode("LEGACYHTML5");
resolver.setCharacterEncoding(CharEncoding.UTF_8);
resolver.setOrder(1);
templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(resolver);
}
#Test
public void testStringResolution() {
String expected = "<div>dave</div>";
String input = "<div th:text=\"${userName}\">Some Username Here!</div>";
IContext context = new StringAndClassLoaderResourceResolver.StringContext(input);
context.getVariables().put("userName", "dave");
String actual = templateEngine.process("redundant", context);
assertEquals(expected, actual);
}
#Test
public void testClasspathResolution(){
IContext context = new Context();
context.getVariables().put("message", "Hello Thymeleaf!");
String actual = templateEngine.process("dummy", context);
String expected = "<h1>Hello Thymeleaf!</h1>";
assertEquals(expected, actual);
}
}
Dummy template file at src/main/resources/mail/dummy.html
<h1 th:text="${message}">A message will go here!</h1>
Note: We used Apache CommonsIO's IOUtils for converting the String to an InputStream
You can implement your own TemplateResolver and IResourceResolver to work with String.
for simple unit tests:
static class TestResourceResolver implements IResourceResolver {
public String content = "";
#Override
public String getName() {
return "TestTemplateResolver";
}
#Override
public InputStream getResourceAsStream(TemplateProcessingParameters templateProcessingParameters,
String resourceName) {
return new ByteArrayInputStream(content.getBytes());
}
}
or just use org.thymeleaf.templateresolver.StringTemplateResolver in Thymeleaf 3
Yep StringTemplateResolver is the way to go.
public class ReportTemplateEngine {
private static TemplateEngine instance;
private ReportTemplateEngine() {}
public static TemplateEngine getInstance() {
if(instance == null){
synchronized (ReportTemplateEngine.class) {
if(instance == null) {
instance = new TemplateEngine();
StringTemplateResolver templateResolver = new StringTemplateResolver();
templateResolver.setTemplateMode(TemplateMode.HTML);
instance.setTemplateResolver(templateResolver);
}
}
}
return instance;
}
}

java.lang.IllegalArgumentException: interface org.jboss.seam.persistence.EntityManagerProxy is not visible from class loader

I have run into a pretty strange error that I can't get my head around.
In short: I have an ImporterBean that should read an xml file and then do stuff.
That ImporterBean is "kickstarted" by a ImporterKicker, but when I start the app
the ApplicationBean and EntityManager in the ImporterBean class are null. They are
not injected into that bean. In the KickerBean the ImporterBean and ApplicationBean are injected properly.
See code below and please tell me what I'm doing wrong(Using seam SEAM 2.2.1.CR2).
#SuppressWarnings({"UnusedDeclaration"})
#Name("importerBean")
#AutoCreate
public class ImporterBean {
private static final FilenameFilter ONLY_XML_FILES = (FilenameFilter) new SuffixFileFilter(".xml");
public static final String IN_DIR = "IN";
public static final String ERROR_DIR = "ERROR";
public static final String PROCESSED_DIR = "PROCESSED";
#In(create = true)
public ApplicationBean applicationBean;
#In
private EntityManager entityManager;
#Asynchronous
#Transactional
public void runImport(#Duration long firstStart, #IntervalDuration long startTimer) {
log.info("<118100>");
File inDir = Doing some file stuff...
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Inner class bean to kick the background tasks.
*/
#Startup
#Scope(APPLICATION)
#Name("importerKicker")
public static class ImporterKicker {
#In(create = true)
public ImporterBean importerBean;
#In(create = true)
public ApplicationBean applicationBean;
#Create
public void scheduleOptimizer() {
final int interval = applicationBean.getImporter118checkInterval();
if (interval != 0) {
importerBean.runImport(30 * MILLIS_PER_SECOND, interval * MILLIS_PER_SECOND);
} else {
}
}
}
}
This error was a symptom of this:
FullTextHibernateSessionProxy is not visible from class loader
Since you are using an Asynchronous call, you cannot use injections like that in an event scoped component.
Instead inside the Asyncrhonous method write:
#Asynchronous
#Transactional
public void runImport(#Duration long firstStart, #IntervalDuration long startTimer) {
EntityManager entityManager = (EntityManager) Component.getInstance("entityManager");
ApplicationBean applicationBean = (ApplicationBean) Component.getInstance("applicationBean",true);
log.info("<118100>");
File inDir = Doing some file stuff...
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Resources