I am new to Vaadin. I am trying to use the GoogleMaps add-on in my project which compiled fine. The challenge however is that I get an exception at runtime which I do not understand. Googling, I found out that I had to compile the WidgetSet. How can this be achieved? Any help in showing me steps will be appreciated. Contents of widgetset.xml and where it should be placed too
Below are my code and the runtime exception I get:
import com.labafrique.creporter.model.ReportModel;
import com.labafrique.creporter.repository.ReportRepository;
import com.vaadin.navigator.View;
import com.vaadin.tapio.googlemaps.GoogleMap;
import com.vaadin.ui.Composite;
import com.vaadin.ui.VerticalLayout;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
/**
*
* #author Javalove
*/
public class View1 extends Composite implements View {
GoogleMap map;
#Autowired
ReportRepository report;
public View1()
{
map = new GoogleMap("", null, "english");
VerticalLayout v = new VerticalLayout();
map.setSizeFull();
v.addComponent(map);
setCompositionRoot(v);
}
public void initMap()
{
List<ReportModel> lx = report.findAllCases();
}
}
And the exception
java.lang.IllegalArgumentException: Unable to create an instance of {0}.
The constructor threw an exception.
at
Related
I'm a newbie and I try to start a Spring application linked to Optaplanner which will solve and place exams on a timetable.
I fixed the various issues with missing jars and I started the app on main.
However, it gives error:
Exception in thread "main" java.lang.ClassCastException: class org.springframework.boot.context.event.ApplicationStartingEvent cannot be cast to class org.springframework.boot.context.event.ApplicationPreparedEvent (org.springframework.boot.context.event.ApplicationStartingEvent and org.springframework.boot.context.event.ApplicationPreparedEvent are in unnamed module of loader 'app')
Here is the TimeTable class :
package models;
import java.util.List;
import org.optaplanner.core.api.domain.solution.PlanningEntityCollectionProperty;
import org.optaplanner.core.api.domain.solution.PlanningScore;
import org.optaplanner.core.api.domain.solution.PlanningSolution;
import org.optaplanner.core.api.domain.solution.ProblemFactCollectionProperty;
import org.optaplanner.core.api.domain.valuerange.ValueRangeProvider;
import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore;
#PlanningSolution
public class Timetable {
#ValueRangeProvider(id = "PeriodeRange")
#ProblemFactCollectionProperty
public List<Periode> periodeList;
#ValueRangeProvider(id = "SalleRange")
#ProblemFactCollectionProperty
public List<Salle> salleList;
#PlanningEntityCollectionProperty
public List<Examen> examenList;
#PlanningScore
public HardSoftScore score;
public void TimeTable(List<Periode> periodeList, List<Salle> roomList,
List<Examen> examenList) {
this.periodeList = periodeList;
this.salleList = roomList;
this.examenList = examenList;
}
public List<Periode> getperiodeList() {
return periodeList;
}
public List<Salle> getsalleList() {
return salleList;
}
public List<Examen> getexamenList() {
return examenList;
}
public HardSoftScore getScore() {
return score;
}
}
And the class that defines the solver :
package models;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import modeles.Timetable;
import org.optaplanner.core.api.solver.SolverJob;
import org.optaplanner.core.api.solver.SolverManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/Timetable")
public class TimetableController {
#Autowired
public SolverManager<Timetable, UUID> solverManager;
#PostMapping("/solve")
public Timetable solve(#RequestBody Timetable problem) {
UUID problemId = UUID.randomUUID();
// Submit the problem to start solving
SolverJob<Timetable, UUID> solverJob = solverManager.solve(problemId, problem);
Timetable solution;
try {
// Wait until the solving ends
solution = solverJob.getFinalBestSolution();
} catch (InterruptedException | ExecutionException e) {
throw new IllegalStateException("Solving failed.", e);
}
return solution;
}
}
And here is the main :
package models;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class TimeTableSpringBootApp {
public static void main(String[] args) {
System.setProperty("spring.devtools.restart.enabled", "false");
SpringApplication.run(TimeTableSpringBootApp.class, args);
}
}
Any answer would be gladly appreciated.
Thank you in advance.
I suspect your project's dependency tree somehow has that spring class ApplicationStartingEvent twice in it's classpath (coming from different jars), which causes the class cast exception.
Try running mvn dependency:tree on your project and the optaplanner spring boot school timetabling quickstart. I suspect you're mixing spring versions in your dependency tree.
The hibernate validations documentation describes how to create ConstraintMappingContributors here.
It states:
You then need to specify the fully-qualified class name of the
contributor implementation in META-INF/validation.xml, using the
property key hibernate.validator.constraint_mapping_contributors. You
can specify several contributors by separating them with a comma.
Given I have many of these, what would be the most appropriate way to auto-discover these i.e. via #Component and add them dynamically at runtime to the ConstrainMappingConfiguration during Spring Boot startup.
For example.. if a developer creates a new ConstraintMappingContributor, it should be picked up and added automatically when spring boot starts, requiring no other file changes.
This is what I came up with, seems to be working for me.
package...
import org.hibernate.validator.spi.cfg.ConstraintMappingContributor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
#Configuration
public class ValidationConfiguration {
private final List<ConstraintMappingContributor> contributors;
public ValidationConfiguration(Optional<List<ConstraintMappingContributor>> contributors) {
this.contributors = contributors.orElseGet(ArrayList::new);
}
#Bean
public LocalValidatorFactoryBean validatorFactory() {
return new ValidatorFactoryBean(this.contributors);
}
}
package...
import org.hibernate.validator.HibernateValidatorConfiguration;
import org.hibernate.validator.internal.cfg.context.DefaultConstraintMapping;
import org.hibernate.validator.spi.cfg.ConstraintMappingContributor;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import javax.validation.Configuration;
import java.util.List;
public class ValidatorFactoryBean extends LocalValidatorFactoryBean {
private final List<ConstraintMappingContributor> contributors;
ValidatorFactoryBean(List<ConstraintMappingContributor> contributors) {
this.contributors = contributors;
}
#Override
protected void postProcessConfiguration(Configuration<?> cfg) {
if (cfg instanceof HibernateValidatorConfiguration) {
HibernateValidatorConfiguration configuration = (HibernateValidatorConfiguration) cfg;
this.contributors.forEach(contributor -> contributor.createConstraintMappings(() -> {
DefaultConstraintMapping mapping = new DefaultConstraintMapping();
configuration.addMapping(mapping);
return mapping;
}));
}
}
}
I invoke it like this...
if(SpringValidatorAdapter.class.isInstance(this.validatorFactory)){
SpringValidatorAdapter.class.cast(this.validatorFactory).validate(entity, errors);
}
I'v implemented a spring-boot aop demo and it runs well, but when I want to use it to load some resource when the project starts, it doesn't work somehow
Aop:
package com.neo.mysql;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
/**
* Created by li_weia on 2017/7/6.
*/
#Aspect
#Component
public class DynamicDataSourceAspect {
#Before("#annotation(VendorSource)")
public void beforeSwitchDS(JoinPoint point){
//获得当前访问的class
Class<?> className = point.getTarget().getClass();
//获得访问的方法名
String methodName = point.getSignature().getName();
//得到方法的参数的类型
Class[] argClass = ((MethodSignature)point.getSignature()).getParameterTypes();
String dataSource = DataSourceContextHolder.DEFAULT_DS;
try {
// 得到访问的方法对象
Method method = className.getMethod(methodName, argClass);
// 判断是否存在#DS注解
if (method.isAnnotationPresent(VendorSource.class)) {
VendorSource annotation = method.getAnnotation(VendorSource.class);
// 取出注解中的数据源名
dataSource = annotation.value();
}
} catch (Exception e) {
e.printStackTrace();
}
// 切换数据源
DataSourceContextHolder.setDB(dataSource);
}
#After("#annotation(VendorSource)")
public void afterSwitchDS(JoinPoint point){
DataSourceContextHolder.clearDB();
}
}
The VendorSource annotation:
package com.neo.mysql;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by li_weia on 2017/7/6.
*/
#Target({ ElementType.METHOD, ElementType.TYPE })
#Retention(RetentionPolicy.RUNTIME)
public #interface VendorSource {
String value() default "vendor-master";
}
It runs well here, I can successfully change datasource by annotation:
package com.neo.web;
import com.neo.entity.SiteEntity;
import com.neo.mapper.ClassMappingDao;
import com.neo.mysql.VendorSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
public class UserController {
private final ClassMappingDao siteMapper;
#Autowired(required = false)
public UserController(ClassMappingDao siteMapper) {
this.siteMapper = siteMapper;
}
#RequestMapping("/getSites")
#VendorSource("vendor-read")
public List<SiteEntity> getUsers() {
return siteMapper.getAllSite();
}
}
but it doesn't work here, the aop method is not invoked at all:
package com.neo.component;
import com.neo.entity.SiteEntity;
import com.neo.mapper.ClassMappingDao;
import com.neo.mysql.VendorSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* Created by li_weia on 2017/7/7.
*/
#Component
public class TestComponent{
private final ClassMappingDao userMapper;
#Autowired(required = false)
public TestComponent(ClassMappingDao userMapper) {
this.userMapper = userMapper;
init();
}
#VendorSource("vendor-read")
public void init() {
List<SiteEntity> sites = userMapper.getAllSite();
for(SiteEntity site: sites){
System.out.println(site.getSite());
}
}
}
You need to fully qualify the annotation, like so:
#Before("execution(public * *(..)) && #annotation(com.neo.mysql.VendorSource)")
private void whatever() {}
Also, as mentioned in my comment above, you need to have spring-boot-starter-aop on classpath. Maybe you already do, but since you didn't say, it's worth mentioning.
Edit:
I didn't notice the real problem before, I wasn't paying attention.
Spring AOP only triggers if you make calls from another class. This is because Spring needs to be able to intercept the call and run the pointcut. Calling the method from constructor is not going to do anything.
You can do a hackish workaround. Create a #PostConstruct void postConstruct() {} method in your class (not constructor), autowire ApplicationContext, and then do MyClassWithInitMethod myClass = context.getBean(MyClassWithInitMethod.class) in the postConstruct method. Then call the method on myClass, and AOP will kick in.
Frankly, I didn't previously check what you are doing in your pointcut, and it's a terrible idea. When multiple threads run, they are going to overwrite the static context, and create a race-condition that you'll then create another question for. Don't do it! Use the factory pattern instead, and inject the DataSourceFactory in the classes that now have the annotation.
I am currently reading Core JavaServer Faces(3e) book.
I am trying to run the ajax spinner code from the 11th chapter of the book.
I am using Oracle enterprise pack for eclipse, weblogic 10.3.5 server & Mojarra impl.
But the UISpinner class is showing the following error message:
“The type UISpinner must implement the inherited abstract method
ClientBehaviorHolder.getClientBehaviors() “
However, as per the jsf spec - UIComponentBase class implements the getClientBehaviors() method which is inherited by the UISpinner class. Still why I am getting this error? Please help.
Here is the UISpinner class implementation:
package com.corejsf;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.faces.component.FacesComponent;
import javax.faces.component.UIInput;
import javax.faces.component.behavior.ClientBehavior;
import javax.faces.component.behavior.ClientBehaviorHolder;
import javax.faces.convert.IntegerConverter;
#FacesComponent("com.corejsf.Spinner")
public class UISpinner extends UIInput implements ClientBehaviorHolder {
private static List<String> eventNames = Arrays.asList("click");
public UISpinner() {
setConverter(new IntegerConverter());
// to convert the submitted value
setRendererType("com.corejsf.JSSpinner");
// this component has a renderer
}
public String getDefaultEventName() { return "click"; }
public Collection<String> getEventNames() { return eventNames; }
}
What you have going on is a little tricky. You are right that UIInput extends UIComponentBase, which does implement getClientBehaviors(). However, you are implementing ClientBehaviorHolder, which has a public getClientBehaviors() method.
The class you are implementing MUST have that method and apparently it can't come from the class you are extending. What I would do is go ahead an implement that method with a simple empty return value like:
return Collections.emptyMap();
I want to test my Jersey resources with the Jersey Test-Framework.
I followed the descriptions provided here
http://blogs.oracle.com/naresh/entry/jersey_test_framework_makes_it
http://zhanghaoeye.javaeye.com/blog/441759
to create a simple example. My example is hosted as git repository on http://github.com/rmetzler/Jersey-Test .
$ mvn jetty:run works as expected but I keep getting NullPointerExceptions when running $ mvn clean test.
java.lang.NullPointerException
at com.sun.jersey.spi.container.ContainerResponse.mapException(ContainerResponse.java:429)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1295)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1239)
at com.sun.jersey.test.framework.impl.container.inmemory.TestResourceClientHandler.handle(TestResourceClientHandler.java:119)
at com.sun.jersey.api.client.Client.handle(Client.java:616)
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:559)
at com.sun.jersey.api.client.WebResource.get(WebResource.java:182)
at example.jersey.spring.MyResourceTest.testMyResource(MyResourceTest.java:30)
...
I bet I made a small mistake that I'm unable to find. I would show my source to another developer but unfortunately I work alone at home. So maybe someone of you could help me?
UPDATE
I created an Eclipse project by running $ mvn eclipse:eclipse . Now when I run the test as JUnit Test in Eclipse it is green. When running it as TestNG Test it fails. So I guess it has something to do with how the test is executed by TestNG.
I did the same thing except for I am using guice, not spring. This is my implementation (sorry, no time to clean up, you'll have to extract the interesting parts yourself). Note that I used a delegate jerseytest class so I can inherit some code from my base test class. Also you have to map the junit pre- and post-methods to testng ones.
Hope this helps a bit.
package mypackage;
import java.io.IOException;
import java.io.StringReader;
import java.net.URI;
import java.net.URL;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.apache.commons.lang.UnhandledException;
import org.apache.xerces.dom.DOMInputImpl;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.FunctionObject;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.w3c.dom.Document;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import static org.fest.assertions.Assertions.assertThat;
import static org.fest.reflect.core.Reflection.staticMethod;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
import com.sun.jersey.spi.container.WebApplication;
import com.sun.jersey.spi.container.WebApplicationFactory;
import com.sun.jersey.test.framework.AppDescriptor;
import com.sun.jersey.test.framework.JerseyTest;
import com.sun.jersey.test.framework.LowLevelAppDescriptor;
import com.sun.jersey.test.framework.impl.container.inmemory.TestResourceClientHandler;
import com.sun.jersey.test.framework.spi.container.TestContainer;
import com.sun.jersey.test.framework.spi.container.TestContainerException;
import com.sun.jersey.test.framework.spi.container.TestContainerFactory;
import com.sun.jersey.test.framework.spi.container.inmemory.InMemoryTestContainerFactory;
import mypackage.StaticConfig;
import mypackage.MediaTypes;
public abstract class JerseyIntegrationTestBase extends TransactionalIntegrationTestBase {
private static final Logger LOG = LoggerFactory.getLogger( JerseyIntegrationTestBase.class );
private static final class GuiceInMemoryTestContainerFactory extends InMemoryTestContainerFactory {
#Override
public TestContainer create( final URI baseUri, final AppDescriptor ad ) {
return new GuiceInMemoryTestContainer( baseUri, (LowLevelAppDescriptor) ad );
}
/**
* Kopie der Klasse im inmemory-Testcontainer von Jersey, leicht an Guice-Injection angepasst. The class defines methods for
* starting/stopping an in-memory test container, and for running tests on the container.
*/
private static class GuiceInMemoryTestContainer implements TestContainer {
final URI baseUri;
final ResourceConfig resourceConfig;
final WebApplication webApp;
/**
* Creates an instance of {#link GuiceInMemoryTestContainer}
*
* #param Base
* URI of the application
* #param An
* instance of {#link LowLevelAppDescriptor}
*/
private GuiceInMemoryTestContainer( final URI baseUri, final LowLevelAppDescriptor ad ) {
this.baseUri = UriBuilder.fromUri( baseUri ).build();
LOG.info( "Creating low level InMemory test container configured at the base URI " + this.baseUri );
resourceConfig = ad.getResourceConfig();
// Falls man mal in Tests die requests und responses sehen möchte:
// this.resourceConfig.getProperties().put( ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS,
// LoggingFilter.class.getName() );
// this.resourceConfig.getProperties().put( ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS,
// LoggingFilter.class.getName() );
resourceConfig.getProperties().putAll( StaticConfig.getJerseyParams() );
webApp = WebApplicationFactory.createWebApplication();
}
#Override
public Client getClient() {
ClientConfig clientConfig = null;
final Set providerSingletons = resourceConfig.getProviderSingletons();
if ( providerSingletons.size() > 0 ) {
clientConfig = new DefaultClientConfig();
for ( final Object providerSingleton : providerSingletons ) {
clientConfig.getSingletons().add( providerSingleton );
}
}
final Client client = clientConfig == null
? new Client( new TestResourceClientHandler( baseUri, webApp ) )
: new Client( new TestResourceClientHandler( baseUri, webApp ), clientConfig );
return client;
}
#Override
public URI getBaseUri() {
return baseUri;
}
#Override
public void start() {
if ( !webApp.isInitiated() ) {
LOG.info( "Starting low level InMemory test container" );
webApp.initiate( resourceConfig, new GuiceContainer( null ).new ServletGuiceComponentProviderFactory(
resourceConfig, IntegrationTestBase.getInjector() ) );
}
}
#Override
public void stop() {
if ( webApp.isInitiated() ) {
LOG.info( "Stopping low level InMemory test container" );
webApp.destroy();
}
}
}
}
private final JerseyTest _jerseyTest;
public JerseyIntegrationTestBase() {
// PackagesResourceConfig.getPackages macht genau das, was wir wollen, ist aber private, daher
// auf die harte Tour...
// FORMATTER: OFF
final String[] packages =
staticMethod( "getPackages" ).withReturnType( String[].class ).withParameterTypes( Map.class )
.in( PackagesResourceConfig.class ).invoke( StaticConfig.getJerseyParams() );
// FORMATTER: ON
_jerseyTest = new JerseyTest( new LowLevelAppDescriptor.Builder( packages ).build() ) {
#Override
protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
return new GuiceInMemoryTestContainerFactory();
}
};
}
/**
* #return
* #see JerseyTest#client().
*/
protected Client client() {
return _jerseyTest.client();
}
#BeforeClass( alwaysRun = true )
public void setUp() throws Exception {
_jerseyTest.setUp();
}
#AfterClass( alwaysRun = true )
public void tearDown() throws Exception {
_jerseyTest.tearDown();
}
}
Because JerseyTest is using #Before annotation from Junit for initialising the application, and you have to extend JerseyTest to enable testng support, like this:
public class JerseyTestNG extends JerseyTest {
#Override
protected Application configure() {
ResourceConfig config = new ResourceConfig(YourService.class);
}
#BeforeClass
public void setUp() {
super.setUp();
}
#AfterClass
public void tearDown() {
super.tearDown();
}
}
#BeforeClass also will make sure all tests within are executed after the Jersey container is ready when using surefire plugin. Otherwise those tests will fail quickly.
and if you want to it read applicationContext-test.xml other than the default one, set one more property to ResourceConfig:
config.setProperties(new HashMap<String, String>() {{
put("contextConfigLocation", "applicationContext-test.xml");
}});
also, adding some features to ClientConfig maybe helpful:
#Override
protected void configureClient(ClientConfig config) {
config.register(LoggingFilter.class);
config.register(MOXyJsonProvider.class);
config.register(new EncodingFeature(GZipEncoder.class));
}
All tested on Jersey 2.6.
A simple example using Jersey + Spring + TestNG + Jetty here:
http://ameethpaatil.blogspot.com/2011/09/restful-webservice-jersey-spring-30x.html