[vaadin]nullPointerExecption when tring to use service in view constructor - vaadin

I am new to vaadin flow. I am trying to create a list view by following tutorial provided on site.
https://vaadin.com/docs/v14/flow/tutorials/in-depth-course/configuring-vaadin-grid
#Route("")
public class MainView extends VerticalLayout {
private ContactService contactService;
private Grid<Contact> grid = new Grid<>(Contact.class);
public MainView(ContactService contactService) {
this.contactService = contactService;
addClassName("list-view");
setSizeFull();
configureGrid();
add(grid);
updateList();
}
private void configureGrid() {
grid.addClassName("contact-grid");
grid.setSizeFull();
grid.setColumns("firstName", "lastName", "email", "status");
}
private void updateList() {
grid.setItems(contactService.findAll());
}
}
Here when i am executing updateList() method i am getting nullPointerExecption on service instance. I tried using repository.findAll() but facing same issue.
To check the if there is issue in service I created REST API and called the same method in service here i am getting proper result. Please help.
This is the error I am getting.
There was an exception while trying to navigate to '' with the exception message 'Error creating bean with name 'com.example.demo.ui.MainView': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.demo.ui.MainView]: Constructor threw exception; nested exception is java.lang.NullPointerException'

Annotate your ContactService implementation with #Service?

Related

Custom Exception class Jenkins Groovy

I created a custom exception class and put it inside src/org/team/pipeline/TestResultFailed.groovy:
package org.team.pipeline
public class TestResultFailed extends Exception {
// Parameterless Constructor
public TestResultFailed() {}
// Constructor that accepts a message
public TestResultFailed(String message) {
super(message);
}
}
The only issue is the class (and thus even exception) cannot be easily imported from shared library to Jenkins pipeline. Therefore, it's not possible to directly throw exception from Jenkins pipeline.
To bypass that, I tried to "wrap" my new exception into shared library function in vars/teamUtils.groovy:
import org.team.pipeline.*
def getTestResultFailedClass() {
return TestResultFailed
}
And then I import and use it in Jenkinsfile as follows:
TestResultFailed = teamUtils.getTestResultFailedClass()
try {
throw new TestResultFailed.TestResultFailed("error")
} catch (TestResultFailed err) {
log.info("Exception caught: ${err}")
}
However, I get this error:
unable to resolve class TestResultFailed.TestResultFailed
and no matter what I tried I'm still getting this error. Any help is very appreciated.

Set deserializing in Spring Native image problem

I'm stuck with a problem on a built Spring Native image:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.http.converter.HttpMessageConversionException: Type definition error: [collection type; class java.util.HashSet, contains [simple type, class java.lang.Object]]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of java.util.HashSet (no Creators, like default constructor, exist): no default no-arguments constructor found
at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 5, column: 14] (through reference chain: com.example.app.payload.request.SignupRequest["roles"])] with root cause
From this description it seems that I need use custom deserializer, but the problem appears only if I run code from native image - same code works perfectly well if run from JAR.
POJOs are very simple:
public class SignupRequest {
#NotBlank
#Size(min = 3, max = 20)
private String username;
#NotBlank
#Size(max = 50)
#Email
private String email;
private Set<String> roles;
#NotBlank
#Size(min = 6, max = 40)
private String password;
// getters & setters no Lombok (but Lombok is in project)
}
Controller uses standard (nothing fancy) annotations:
public ResponseEntity<MessageResponse> registerUser(#Valid #RequestBody SignupRequest signUpRequest)
Has anyone encountered a similar problem?
Finally I found missing part - I have to add HashSet to SerializationHint:
#SpringBootApplication
#SerializationHint(types = {
java.util.HashSet.class
})
public class SpringNativeApplication {
public static void main(String[] args) {
// ...
}
}

Spring elasticsearch java.net.UnknownHostException

Trying to update a small experimental Spring Elasticsearch project to reflect changes in the 3.2.6 release reference guide.
As noted: TransportClient is deprecated as of Elasticsearch 7 and will be removed in 8. Trying to reconfig to High Level Rest Client.
But getting the following errors
Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'elasticDatasource' defined in file [/Users/erichuang/Desktop/JE/00-Development/dev/lab/lab-elastic-search/lab-elastic-search/target/classes/com/elastic/labelasticsearch/config/ElasticDatasource.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'carElasticRepo': Invocation of init method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository]: Constructor threw exception; nested exception is org.springframework.data.elasticsearch.ElasticsearchException: Error while for indexExists request: org.elasticsearch.action.admin.indices.get.GetIndexRequest#b5d8ebb
org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
com.elastic.labelasticsearch.LabElasticSearchApplication.main(LabElasticSearchApplication.java:15)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'carElasticRepo': Invocation of init method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository]: Constructor threw exception; nested exception is org.springframework.data.elasticsearch.ElasticsearchException: Error while for indexExists request: org.elasticsearch.action.admin.indices.get.GetIndexRequest#b5d8ebb
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796)
... 24 common frames omitted
Caused by: java.net.UnknownHostException: localhost/<unresolved>: nodename nor servname provided, or not known
at java.base/java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
at java.base/java.net.InetAddress$PlatformNameService.lookupAllHostAddr(InetAddress.java:932)
at java.base/java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1505)
at java.base/java.net.InetAddress$NameServiceAddresses.get(InetAddress.java:851)
at java.base/java.net.InetAddress.getAllByName0(InetAddress.java:1495)
at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1354)
at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1288)
...
... 63 common frames omitted
Old setup (works)
ElasticSearchConfig
#Configuration
#EnableElasticsearchRepositories(basePackages = "com.elastic.labelasticsearch.repo")
public class ElasticSearchConfig {
private static final String esHost = "localhost";
private static final int esPort = 9300;
#Bean
public Client client() throws UnknownHostException {
var transportClient = new PreBuiltTransportClient(Settings.EMPTY);
transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName(esHost), esPort));
return transportClient;
}
#Bean(name ={"elasticsearchOperations", "elasticsearchTemplate"})
public ElasticsearchOperations esTemplate() throws UnknownHostException {
return new ElasticsearchTemplate(client());
}
#Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
New Setup
#Configuration
#EnableElasticsearchRepositories(basePackages = "com.elastic.labelasticsearch.repo")
public class RestClientConfig extends AbstractElasticsearchConfiguration {
#Override
#Bean
public RestHighLevelClient elasticsearchClient() {
final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
.connectedTo("localhost:9300")
.build();
return RestClients.create(clientConfiguration).rest();
}
}
What am I missing?
This is a bug resulting from as change in Java 14 in the java.net.InetSocketAddress.toString() method. This has been fixed in 4.0.RC2 (released yesterday).
Edit: I will backport this into the 3.2 branch as well
You will need to configure your bean using this way that allow to separate the host port and http protocol used:
#Configuration
#EnableElasticsearchRepositories(basePackages = "*")
public class ElasticsearchClientConfig {
#Value("${elasticsearch.host}")
private String host;
#Value("${elasticsearch.port}")
private int port;
#Value("${elasticsearch.protocol}")
private String protocol;
#Value("${elasticsearch.username}")
private String userName;
#Value("${elasticsearch.password}")
private String password;
#Bean(destroyMethod = "close")
public RestHighLevelClient restClient() {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
RestClientBuilder builder = RestClient.builder(new HttpHost(host, port, protocol)).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
RestHighLevelClient client = new RestHighLevelClient(builder);
return client;
}
}

How to access toolbar items from ViewModel Xamarin forms

I tried to set padge in toolbar item from viewmodel
I have interface called IToolbarItemBadgeService
public interface IToolbarItemBadgeService
{
void SetBadge(Page page, ToolbarItem item, string value, Color backgroundColor, Color textColor);
}
I want to set badge in toolbar item i used this code after i Register the interface but it throw exception
private IToolbarItemBadgeService _toolbarItemBadge;
and in the constructor
public MainTabPageViewModel(IToolbarItemBadgeService toolbarItemBadge)
{
_toolbarItemBadge = toolbarItemBadge;
_toolbarItemBadge.SetBadge(MainTabPage.Main,MainTabPage.Main.ToolbarItems.FirstOrDefault() , $"{BaseService.CartCounter}", Color.Orange, Color.White);
}
Exception is thrown :
Unity.Exceptions.ResolutionFailedException: Resolution of the
dependency failed, type = 'System.Object', name = 'MainTabPage'.
Exception occurred while: Calling constructor
LGMobileApp.Views.MainTabPage(). Exception is:
ResolutionFailedException - Resolution of the dependency failed, type
= 'LGMobileApp.ViewModels.MainTabPageViewModel', name = '(none)'. Exception occurred while: Calling constructor
LGMobileApp.ViewModels.MainTabPageViewModel(Prism.Navigation.INavigationService
navigationService, LGMobileApp.Helpers.IToolbarItemBadgeService
toolbarItemBadge). Exception is: NullReferenceException - Object
reference not set to an instance of an object.
From exception you can see that your service is not registred and it can not be resolved.
You will need to register your IToolbarItemBadgeService interface, with implemenation inside of App.cs in RegisterTypes method.
Something like this:
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.Register<IToolbarItemBadgeService, ToolbarItemBadgeService>();
// .. Other registration code
}
After this, you will be able to use IToolbarItemBadgeService which is injected in your MainTabPageViewModel.
Wishing you lots of luck with coding!

Circular reference trying to configure custom permission evaluator in spring security

I'm trying to configure a custom permission evaluator but whenever the app starts up it's complaining of a circular reference.
The configuration code is:
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
private static Logger logger = LogManager.getLogger(MethodSecurityConfig.class.getName());
#Autowired
DataSource dataSource;
#Autowired
Environment env;
#Autowired
AuthenticationManager auth;
public MethodSecurityConfig() {
logger.debug("Loading method security config.");
}
#Override
protected AuthenticationManager authenticationManager() throws Exception {
return auth;
}
/**
* Override to set up the custom expression handler.
* #return The custom expression handler
*/
#Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
return expressionHandler();
}
/**
* Defines a custom permission evaluator to evaluate the access permissions for Spring security.
* #return The default expression handler configured with a custom permission evaluator.
*/
#Bean
public DefaultMethodSecurityExpressionHandler expressionHandler(){
DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
handler.setPermissionEvaluator(permissionEvaluator());
return handler;
}
/**
* Custom implementation of a permission evaluator
* #return An instance of {#link BasePermissionEvaluator}
*/
#Bean
public PermissionEvaluator permissionEvaluator() {
return new BasePermissionEvaluator();
}
}
When the app start up this exception occurs:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'methodSecurityConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration.setPermissionEvaluator(java.util.List); nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'permissionEvaluator': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[AutowiredAnnotationBeanPostProcessor.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) ~[AbstractAutowireCapableBeanFactory.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[AbstractAutowireCapableBeanFactory.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[AbstractAutowireCapableBeanFactory.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305) ~[AbstractBeanFactory$1.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[DefaultSingletonBeanRegistry.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301) ~[AbstractBeanFactory.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196) ~[AbstractBeanFactory.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:368) ~[ConstructorResolver.class:4.2.1.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(A
What am I doing wrong here? I tried various things like adding the AuthenticationManager. Is there something else I need to override?
I had faced the same issue. In my case the reason was there was another security configuration class which has #EnableGlobalMethodSecurity annotation. Removing that annotation solved the issue.
The reason to have two security configuration classes is described here.
To my understanding this happens when Spring first processes the other configuration class, because of #EnableGlobalMethodSecurity permissionEvaluator and similar beans are registered that time and later when this configuration class is processed we got this error.
Also looks like this behaviour is arbitrary, depends on which configuration class is first processed based on classpath ordering.

Resources