Java.lang.error? - blackberry

I encountered a error Java.lang.error when trying to access a static function in a class.
class Global
{
public Global(){}
public static void Init()
{
//doing something
}
}
I use Global class here:
public class MyApp extends UiApplication
{
public static void main(String[] args)
{
MyApp app = new MyApp ();
app.enterEventDispatcher();
}
public MyApp ()
{
//invoke
Global.Init(); //throw Java.lang.error
}
}
The error is thrown whenever I access any static properties in class Global.

Syntax errors:
Class instead of class
Global() instead of Global
I suggest you read a Java Tutorial.

An Error is thrown if an unrecoverable problem is detected. Something bad must be happening in your Init method.

I use Global class here:
public class MyApp extends UiApplication
{
public static void main(String[] args)
{
MyApp app = new MyApp ();
app.enterEventDispatcher();
}
public MyApp ()
{
Global.Init();
}
}
Especially, The error was thrown whenever I access any static properties in class Global.
Thank all!

Related

Vaadin 23 override internal error message

when an error occurs inside the application, the user sees the following message:
Is it possible to override it?
I aaded the following:
public class CustomErrorHandler implements ErrorHandler {
private static final Logger logger = LoggerFactory.getLogger(CustomErrorHandler.class);
#Override
public void error(ErrorEvent errorEvent) {
logger.error("Something wrong happened", errorEvent.getThrowable());
Notification.show("An internal error has occurred. Please contact support.");
if (UI.getCurrent() != null) {
UI.getCurrent().access(() -> {
Notification.show("An internal error has occurred. Please contact support.");
});
}
}
}
#Component
public class ServiceListener implements VaadinServiceInitListener {
private static final Logger logger = LoggerFactory.getLogger(LanguageReceiver.class);
#Override
public void serviceInit(ServiceInitEvent event) {
event.getSource().addSessionInitListener(
initEvent -> {
logger.info("A new Session has been initialized!");
VaadinSession.getCurrent().setErrorHandler(new CustomErrorHandler());
});
event.getSource().addUIInitListener(
initEvent -> logger.info("A new UI has been initialized!"));
}
}
#ParentLayout(MainLayout.class)
#AnonymousAllowed
public class ExceptionHandler extends VerticalLayout implements HasErrorParameter<Exception> {
static final Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);
#Override
public int setErrorParameter(BeforeEnterEvent event, ErrorParameter<Exception> parameter) {
logger.error("Error", parameter.getException());
Label label = new Label(parameter.getException().getMessage());
add(label);
return HttpServletResponse.SC_NOT_FOUND;
}
}
but still unable to override the mentioned error on the screenshot above. Please show how to do this.
Generally, you need to extend SystemMessages and override getInternalErrorMessage().
Then you can register it using:
YourSystemMessages sysMessages = new YourSystemMessages();
VaadinService.getCurrent().setSystemMessagesProvider(systemMessagesInfo -> sysMessages);
and if you want to reset it to the default one:
VaadinService.getCurrent().setSystemMessagesProvider(DefaultSystemMessagesProvider.get());
In a Spring Boot based application you can register it in any implementation of VaadinServiceInitListener such as:
#Component
public class CustomSystemMessagesInitializer implements VaadinServiceInitListener {
#Autowired
private YourSystemMessages sysMessages;
// You can provide your SystemMessages instance in any way that suits you.
#Override
public void serviceInit(ServiceInitEvent serviceInitEvent) {
serviceInitEvent.getSource()
.setSystemMessagesProvider(systemMessagesInfo -> sysMessages);
}
}
Note that serviceInitEvent.getSource() returns the VaadinService instance, so it can be used as the reference as an alternative to VaadinService.getCurrent.

Run code in Vaadin 8 application idependent of UI

In earlier versions, you could have a class which implements ServletContextListener and put your code in the contextInitialized method, so that it runs when the server starts. This is useful for loading up the database into memory. How does one achieve this in a Vaadin 8 project?
In exactly the same way: By registering a ServletContextListener. You can use the #WebListener annotation for this. For example:
public class WebConfig {
#WebServlet("/*")
#VaadinServletConfiguration(ui = VaadinUI.class, productionMode = false)
public static class JdbcExampleVaadinServlet extends VaadinServlet {
}
#WebListener
public static class JdbcExampleContextListener implements ServletContextListener {
#Override
public void contextInitialized(ServletContextEvent sce) {
try {
DatabaseService.init();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void contextDestroyed(ServletContextEvent sce) {
DatabaseService.shutdown();
}
}
}

How can Initialize My AutoMapper with my configs

Here is My Code :
My Initializer Class
public class Initializer : IMapInitializer
{
IMapInitializer _mapInitializer;
public Initializer(IMapInitializer mapInitializer)
{
_mapInitializer = mapInitializer;
}
public void Initialize()
{
Mapper.Initialize(config =>
{
config.CreateMap<OrderMain, OrderDO>().ReverseMap();
//Others
.....
});
}
}
Here is IMapInitializer
public interface IMapInitializer
{
void Initialize();
}
What can i do in Startup.cs ? I have tried service.AddTransient()
You can just call Mapper.Initialize once in your Startup.Configure method, there's no need to involve the DI container:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
Mapper.Initialize(c =>
{
c.CreateMap<Order, OrderDto>();
c.CreateMap<SomethingElse, SomethingElseDto>();
//etc...
});
//snip...
}
Your mappings will then be available whenever you call map:
var dto = Mapper.Map<OrderDto>(myOrder);
Edit
So if you do want to initialise your mappings via a class registered in the DI container, you'd do the following:
Define your interface (exactly as you have already):
public interface IMapInitializer
{
void Initialize();
}
Implement it, you just need the implementation of the interface and you'd only need to include other interfaces in the constructor if you wanted to inject different dependencies into your Initializer class (e.g. a logger which would also need registering with the DI container):
public class Initializer : IMapInitializer
{
public void Initialize()
{
Mapper.Initialize(config =>
{
config.CreateMap<OrderMain, OrderDTO>().ReverseMap();
//Others
});
}
}
Then register this in the DI container with either AddTransient (your class will be created whenever it's needed), AddScoped (created once per request) or AddSingleton (once per the lifetime of the app). I'm using scoped here as you'll likely just want to use this once anyway as once you've created your mappings they'll be available for the life of your app anyway:
services.AddScoped<IMapInitializer, Initializer>();
Now you can use the DI container to inject the above into whatever requires it, e.g. into a controller:
public class MyController : Controller
{
private IMapInitializer _initializer = null;
public MyController(IMapInitializer initializer)
{
_initializer = initializer ?? throw new ArgumentException(nameof(initializer));
}
public IActionResult Get()
{
//initialize - although once you've done this you don't need to do so again!
initializer.Initialize();
//use mappings...
}
}
I create static initializer will be called from ConfigureServices
public static class MapperInitializer
{
public static void MapperConfiguration()
{
Mapper.Initialize(config =>
{
//Configs..
});
}
}
I do like this.
public void ConfigureServices(IServiceCollection services)
{
MapperInitializer.MapperConfiguration();
}
Completed. Thanks

Jedis Cache implementation without JedisPool/commons-pool2-2.0

How to implement Jedis without JedisPool/commons-pool2-2.0 because still we are using jdk 1.5(commons-pool2-2.0 does not support JDK 1.5)
How to implement a thread-safe connection pooling?
I'm not sure about Jedis compatibility with Java 5. You can create your own pooling based on the older commons-pool 1.6 library. You do not need to have commons-pool2 on your class path to run jedis. I used Jedis 2.7.3 and commons-pool 1.6 to validate the solution approach.
Find the example code attached:
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.PoolableObjectFactory;
import org.apache.commons.pool.impl.GenericObjectPool;
import redis.clients.jedis.Jedis;
public class JedisWithOwnPooling {
public static void main(String[] args) throws Exception {
ObjectPool<Jedis> pool = new GenericObjectPool(new JedisFactory("localhost"));
Jedis j = pool.borrowObject();
System.out.println(j.ping());
pool.returnObject(j);
pool.close();
}
private static class JedisFactory implements PoolableObjectFactory<Jedis> {
private String host;
/**
* Add fields as you need. That's only an example.
*/
public JedisFactory(String host) {
this.host = host;
}
#Override
public Jedis makeObject() throws Exception {
return new Jedis(host);
}
#Override
public void destroyObject(Jedis jedis) throws Exception {
jedis.close();
}
#Override
public boolean validateObject(Jedis jedis) {
return jedis.isConnected();
}
#Override
public void activateObject(Jedis jedis) throws Exception {
if (!jedis.isConnected()) {
jedis.connect();
}
}
#Override
public void passivateObject(Jedis jedis) throws Exception {
}
}
}

DataSourceInitializer : ApplicationEventMulticaster is not initialized

I am using Spring Boot 1.2.0 with embedded h2database.
The database is initialized using schema.sql file in the classpath.
It worked fine until I added #EnableGlobalMethodSecurity annotation to the WebSecurityConfiguration class.
java.lang.IllegalStateException: ApplicationEventMulticaster not initialized exception is thrown from DataSourceInitializer.runSchemaScripts
What may be the problem ?
Here is the code:
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
#EnableGlobalMethodSecurity(securedEnabled = true)
#Configuration
class WebSecurityConfiguration extends GlobalAuthenticationConfigurerAdapter {
#Autowired
DataSource dataSource;
#Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource);
}
}
I think the solution is to not use the init method to setup JDBC authentication. Try with a separate class that extends GlobalAuthenticationConfigurerAdapter and override the config method.

Resources