Handling MaxUploadSizeExceededException in Spring webapp - eclipse

I'm trying to handle maximum upload size exception but all solutions i found failed, I tried implementing HandlerExceptionResolver, #ControllerAdvice and method annotated by #ExceptionHandler(MaxUploadSizeExceededException.class) but nothning helped.
Among the answers to similar questions i found out that it could be because the exception is thrown before the controller is even called but i don't have such insight into this issue so i can't solve it on my own.
Stack trace:
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size of 500000 bytes exceeded; nested exception is org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (1065736) exceeds the configured maximum (500000)
at org.springframework.web.multipart.commons.CommonsMultipartResolver.parseRequest(CommonsMultipartResolver.java:160)
at org.springframework.web.multipart.commons.CommonsMultipartResolver.resolveMultipart(CommonsMultipartResolver.java:139)
at org.springframework.web.multipart.support.MultipartFilter.doFilterInternal(MultipartFilter.java:110)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:106)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (1065736) exceeds the configured maximum (500000)
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:965)
at org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:310)
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:334)
at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:115)
at org.springframework.web.multipart.commons.CommonsMultipartResolver.parseRequest(CommonsMultipartResolver.java:156)
... 20 more
and some parts of my code that handle Multipart resolving and so on ...
SecurityWebAppInitializer.class - I suspect this MultipartFilter might be part of the problem but it has to be there because of this http://docs.spring.io/spring-security/site/docs/3.2.0.CI-SNAPSHOT/reference/html/csrf.html#csrf-multipartfilter
#Order(1)
public class SecurityWebAppInitializer extends AbstractSecurityWebApplicationInitializer {
#Override
protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(servletContext, new MultipartFilter());
}
}
Multipart Configuration
#Configuration
public class MultipartConfig {
#Bean
public MultipartResolver filterMultipartResolver() {
CommonsMultipartResolver filterMultipartResolver = new CommonsMultipartResolver();
filterMultipartResolver.setMaxUploadSize(500000);
return filterMultipartResolver;
}
}
WebAppInitializer.class
#Order(2)
public class WebAppInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] {MultipartConfig.class, SecurityConfig.class, PersistenceConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { DispatcherConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
#Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
return new Filter[] { characterEncodingFilter};
}
}
If you need some other parts of webapp just ask.
Thanks in advance

if you do not know max upload size then don't set the max upload size.
If you want to restrict the MAX upload size then you need to consider otherwise comment it
Below I have commented the setter to set max upload size.
#Configuration
public class MultipartConfig {
#Bean
public MultipartResolver filterMultipartResolver() {
CommonsMultipartResolver filterMultipartResolver = new CommonsMultipartResolver();
//filterMultipartResolver.setMaxUploadSize(500000);
return filterMultipartResolver;
}
}

I captured it by this class:
#Controller
public class ExceptionHandlerController implements ErrorController, HandlerExceptionResolver{
private static final String PATH = "/error";
Logger log = LoggerFactory.getLogger(ExceptionHandlerController.class);
public String getErrorPath() {
return PATH;
}
#Override
public ModelAndView resolveException(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception exception) {
log.debug("Captured....");
Map<Object, Object> model = new HashMap<Object, Object>();
//all the exception is here and u can specified it by this exception: MaxUploadSizeExceededException
return new ModelAndView("Error", (Map) model);
}
}
I used SpringBoot, so it require me to implements ErrorController. If you don't then do not need to implement it.
Hope it help for someone looking for this situation.

Related

How to identify the path of the infinispan configuration xml file

I am a newbie to infinispan and would like to seek help about issue below.
I tried to start a infinispan cache on an ejb, such that it should be shared among several applications.
#Singleton
public class CSysAppCacheServiceImpl implements CSysAppCacheService {
private DefaultCacheManager cacheManager;
private Cache testingCache;
#EJB(name = "postService")
private CSysPostDao postService;
#EJB(name = "roleService")
private CSysRoleDao roleService;
protected Map<String, List<CSysRole>> sysRoleMap;
protected Map<String, List<CSysPost>> sysPostMap;
protected List<CSysRole> sysRoleList;
protected List<CSysPost> sysPostList;
#PostConstruct
public void init() {
// perform some initialization logic
try {
System.out.println("init CacheManager start");
cacheManager = new DefaultCacheManager("/demo-infinispan.xml");
System.out.println("init CacheManager end");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
testingCache = cacheManager.getCache("testingCache");
preloadCache();
}
// Pre-load cache when server startup
public void preloadCache() {
for (CacheKey ck : CacheKey.values()) {
resetCache(ck);
}
}
public void resetCache(CacheKey key) {
if (key == null) {
for (CacheKey ck : CacheKey.values()) {
resetCache(ck);
}
} else if (key.equals(CacheKey.SYS_ROLE_LIST)) {
this.sysRoleList = roleService.findAllRole();
setupCacheList(CacheKey.SYS_ROLE_LIST, sysRoleList);
} else if (key.equals(CacheKey.SYS_POST_LIST)) {
this.sysPostList = postService.findAllPost();
setupCacheList(CacheKey.SYS_POST_LIST, sysPostList);
}
}
protected <T> void setupCacheList(CacheKey key, List<T> list) {
testingCache.put(key, list);
}
public List<Object> getCacheList(CacheKey key) {
return (List<Object>) testingCache.get(key);
}
public List<Object> getCacheList(String keyString) {
return (List<Object>) testingCache.get(keyString);
}
#SuppressWarnings("unchecked")
public <K, V> Map<K, V> getCacheMap(CacheKey key) {
return (Map<K, V>) testingCache.get(key);
}
public Map<String, List<CSysRole>> getCSysRoleMap() {
sysRoleMap = getCacheMap(CacheKey.SYS_ROLE_LIST);
if (MapUtils.isEmpty(sysRoleMap)) {
resetCache(CacheKey.SYS_ROLE_LIST);
}
return sysRoleMap;
}
public Map<String, List<CSysPost>> getCSysPostMap() {
sysRoleMap = getCacheMap(CacheKey.SYS_POST_LIST);
if (MapUtils.isEmpty(sysPostMap)) {
resetCache(CacheKey.SYS_POST_LIST);
}
return sysPostMap;
}
}
The ejb is init via following class
#ViewScoped
#Named
public class CacheView implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger logger = LogManager.getLogger(CacheView.class);
public static final String FNCT_ID = "SAMPLCACH";
private List<String> cacheKeyList;
// private Map<K, V> selectedMap;
private CacheKey selectedKey;
private List<Object> selectedList;
#EJB CSysAppCacheService appScopeCache;
#PostConstruct
public void init() {
appScopeCache.init();
}
...
}}}}
But when the application start, following exception raised
Caused by: java.lang.NoClassDefFoundError: org/jboss/marshalling/ClassResolver
at org.infinispan.configuration.global.SerializationConfiguration.<clinit>(SerializationConfiguration.java:16)
at org.infinispan.configuration.global.SerializationConfigurationBuilder.<init>(SerializationConfigurationBuilder.java:27)
at org.infinispan.configuration.global.GlobalConfigurationBuilder.<init>(GlobalConfigurationBuilder.java:43)
at org.infinispan.configuration.parsing.ConfigurationBuilderHolder.<init>(ConfigurationBuilderHolder.java:25)
at org.infinispan.configuration.parsing.ParserRegistry.parse(ParserRegistry.java:122)
at org.infinispan.manager.DefaultCacheManager.<init>(DefaultCacheManager.java:311)
at org.infinispan.manager.DefaultCacheManager.<init>(DefaultCacheManager.java:286)
at org.infinispan.manager.DefaultCacheManager.<init>(DefaultCacheManager.java:274)
at CSysAppCacheServiceImpl.init(CSysAppCacheServiceImpl.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.jboss.as.ee.component.ManagedReferenceLifecycleMethodInterceptor.processInvocation(ManagedReferenceLifecycleMethodInterceptor.java:96)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.weld.interceptors.Jsr299BindingsInterceptor.doLifecycleInterception(Jsr299BindingsInterceptor.java:122)
at org.jboss.as.weld.interceptors.Jsr299BindingsInterceptor.processInvocation(Jsr299BindingsInterceptor.java:111)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:509)
at org.jboss.weld.module.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:72)
at org.jboss.as.weld.ejb.EjbRequestScopeActivationInterceptor.processInvocation(EjbRequestScopeActivationInterceptor.java:89)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.weld.injection.WeldInjectionInterceptor.processInvocation(WeldInjectionInterceptor.java:53)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.ee.component.ManagedReferenceFieldInjectionInterceptorFactory$ManagedReferenceFieldInjectionInterceptor.processInvocation(ManagedReferenceFieldInjectionInterceptorFactory.java:112)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.ee.component.ManagedReferenceFieldInjectionInterceptorFactory$ManagedReferenceFieldInjectionInterceptor.processInvocation(ManagedReferenceFieldInjectionInterceptorFactory.java:112)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.ee.component.AroundConstructInterceptorFactory$1.processInvocation(AroundConstructInterceptorFactory.java:28)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.weld.injection.WeldInterceptorInjectionInterceptor.processInvocation(WeldInterceptorInjectionInterceptor.java:56)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.weld.interceptors.Jsr299BindingsCreateInterceptor.processInvocation(Jsr299BindingsCreateInterceptor.java:105)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.ee.component.NamespaceContextInterceptor.processInvocation(NamespaceContextInterceptor.java:50)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInOurTx(CMTTxInterceptor.java:237)
... 150 more
The problem should be at line
cacheManager = new DefaultCacheManager("/demo-infinispan.xml");
the xml is just a simple standlone cache as below
<?xml version="1.0" encoding="UTF-8"?>
<infinispan
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:infinispan:config:9.0 http://www.infinispan.org/schemas/infinispan-config-9.0.xsd"
xmlns="urn:infinispan:config:9.0">
<cache-container name="testing" default-cache="default">
<local-cache name="default">
<eviction max-entries="5000" strategy="LIRS" />
</local-cache>
</cache-container>
</infinispan>
I tried to put the demo-infinispan.xml in either of the following path, but still exception raised
1) same folder of the java bean
2) src folder of the package
3) same folder of the view bean
Would anyone advise where the xml should I put?
Thanks.
Best Regards,
The issue is solved due to missing libraries

How to create mock object of such method which return type is List<Tuple>

I am trying to write test case for Account Controller. At very first My I am creating mock object but that methods return type is List<Tuple>. I am not getting how to create mock object of following method which return type is List
Can any one tell me how to create mock object for following method?
AccountController
#GetMapping("/findAccountData")
public ResponseEntity<List<Tuple>> populateGridViews(#RequestParam(value="sClientAcctId",required=false) String sClientAcctId,
#RequestParam(value="sAcctDesc",required=false) String sAcctDesc,
#RequestParam(value="sInvestigatorName",required=false)String sInvestigatorName,
#RequestParam(value="sClientDeptId",required=false) String sClientDeptId) throws Exception {
return ResponseEntity.ok(accService.populateGridViews(sClientAcctId, sAcctDesc,sInvestigatorName,sClientDeptId));
}
AccountService
public List<Tuple> populateGridViews(String sClientAcctId, String sAcctDesc, String sInvestigatorName,
String sClientDeptId)throws Exception{
QAccount account = QAccount.account;
QDepartment department = QDepartment.department;
QAccountCPCMapping accountCPCMapping = QAccountCPCMapping.accountCPCMapping;
QInvestigator investigator = QInvestigator.investigator;
JPAQuery<Tuple> query = new JPAQuery<Tuple>(em);
query.select(Projections.bean(Account.class, account.sClientAcctId, account.sAcctDesc, account.sLocation,
Projections.bean(Department.class, department.sDeptName, department.sClientDeptId).as("department"),
Projections.bean(Investigator.class, investigator.sInvestigatorName).as("investigator"),
Projections.bean(AccountCPCMapping.class, accountCPCMapping.sCCPCode).as("accountCPC"))).from(account)
.innerJoin(account.department, department).innerJoin(account.accountCPC, accountCPCMapping)
.innerJoin(account.investigator, investigator);
if (StringUtils.isNotEmpty(sClientAcctId)) {
query.where(account.sClientAcctId.equalsIgnoreCase(sClientAcctId));
}
// code.......
return query.fetch();
}
AccountControllerTest
#RunWith(SpringRunner.class)
public class TestAccountController {
private MockMvc mockMvc;
#Mock
private AccountService accountService;
#InjectMocks
private AccountController accountController;
#Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(accountController).build();
}
#Test
public void populateGridViewsTest() throws Exception {
String sClientAcctId = "1122";
String sAcctDesc = "SRI";
String sInvestigatorName = "Ram";
String sClientDeptId = "1200";
Tuple mockedTuple = Mockito.mock(Tuple.class);
List<Tuple> accountObj = new ArrayList<>();
accountObj.add(mockedTuple);
Mockito.when(accountService.populateGridViews(sClientAcctId, sAcctDesc, sInvestigatorName, sClientDeptId))
.thenReturn(accountObj);
mockMvc.perform(
get("/spacestudy/$ InstituteIdentifier/admin/account/findAccountData")
.param("sClientAcctId", "1122")
.param("sAcctDesc", "SRI")
.param("sInvestigatorName", "Ram")
.param("sClientDeptId", "1200")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(print());
Mockito.verify(accountService).populateGridViews(sClientAcctId, sAcctDesc, sInvestigatorName, sClientDeptId);
}
Stack Trace
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
at com.spacestudy.controller.AccountControllerTest.populateGridViewsTest(AccountControllerTest.java:57)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
#RunWith(SpringRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
public class TestAccountController {
#Autowired
private MockMvc mockMvc;
#Autowired
private AccountService accountService;
#Autowired
private AccountController accountController;
#Test
#Transactional
public void populateGridViewsTest() throws Exception {
String sClientAcctId = "1122";
String sAcctDesc = "SRI";
String sInvestigatorName = "Ram";
String sClientDeptId = "1200";
Tuple mockedTuple = Mockito.mock(Tuple.class);
List<Tuple> accountObj = new ArrayList<>();
accountObj.add(mockedTuple);
Mockito.when(accountService.populateGridViews(sClientAcctId, sAcctDesc, sInvestigatorName, sClientDeptId))
.thenReturn(accountObj);
mockMvc.perform(
get("/spacestudy/$ InstituteIdentifier/admin/account/findAccountData")
.param("sClientAcctId", "1122")
.param("sAcctDesc", "SRI")
.param("sInvestigatorName", "Ram")
.param("sClientDeptId", "1200")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(print());
Mockito.verify(accountService).populateGridViews(sClientAcctId, sAcctDesc, sInvestigatorName, sClientDeptId);
}
#AutoConfigureMockMvc
public class TickServiceTest {
#Autowired
private MockMvc mockMvc;
}
First you have to try this..instead of using Mockito use MockMvc object. And just tell me u want to create AccountController object or Account bean object?
You can implements Tuple interface and use it in thenReturn method.
import java.util.Arrays;
import com.querydsl.core.Tuple;
import com.querydsl.core.types.Expression;
public class MockedTuple implements Tuple {
private final Object[] a;
public MockedTuple(Object[] a) {
this.a = a;
}
#SuppressWarnings("unchecked")
#Override
public <T> T get(int index, Class<T> type) {
return (T) a[index];
}
#Override
public <T> T get(Expression<T> expr) {
return null;
}
#Override
public int size() {
return a.length;
}
#Override
public Object[] toArray() {
return a;
}
#Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (obj instanceof Tuple) {
return Arrays.equals(a, ((Tuple) obj).toArray());
} else {
return false;
}
}
#Override
public int hashCode() {
return Arrays.hashCode(a);
}
#Override
public String toString() {
return Arrays.toString(a);
}
}
Example of test:
Object[] myReturnedObject = new Object[1];
myReturnedObject[0] = value;
when(myService.getTuples(...params)).thenReturn(
List.of(new MockedTuple(myReturnedObject))
)

Bulk operations in CassandraRepository for spring-data-cassandra 2.0M1

I have a simple spring-data-cassandra project that tries to insert multiple entities using
<S extends T> Iterable<S> save(Iterable<S> entities)
of the CassandraRepository class.
However when I use version 2.0.0.M1 (works in previous versions), I get the following error,
Exception in thread "main" org.springframework.data.cassandra.mapping.VerifierMappingExceptions: java.util.ArrayList:
- Cassandra entities must be annotated with either #Persistent, #Table, #UserDefinedType or #PrimaryKeyClass
at org.springframework.data.cassandra.mapping.CompositeCassandraPersistentEntityMetadataVerifier$PersistentAnnotationVerifier.verify(CompositeCassandraPersistentEntityMetadataVerifier.java:92)
at org.springframework.data.cassandra.mapping.CompositeCassandraPersistentEntityMetadataVerifier.verify(CompositeCassandraPersistentEntityMetadataVerifier.java:70)
at org.springframework.data.cassandra.mapping.BasicCassandraPersistentEntity.verify(BasicCassandraPersistentEntity.java:160)
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:332)
at org.springframework.data.cassandra.mapping.BasicCassandraMappingContext.addPersistentEntity(BasicCassandraMappingContext.java:381)
at org.springframework.data.cassandra.mapping.BasicCassandraMappingContext.addPersistentEntity(BasicCassandraMappingContext.java:65)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:185)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:145)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:70)
at org.springframework.data.cassandra.core.CassandraTemplate.getPersistentEntity(CassandraTemplate.java:427)
at org.springframework.data.cassandra.core.CassandraTemplate.getTableName(CassandraTemplate.java:443)
at org.springframework.data.cassandra.core.CassandraTemplate.insert(CassandraTemplate.java:314)
at org.springframework.data.cassandra.core.CassandraTemplate.insert(CassandraTemplate.java:302)
at org.springframework.data.cassandra.repository.support.SimpleCassandraRepository.save(SimpleCassandraRepository.java:66)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.executeMethodOn(RepositoryFactorySupport.java:553)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:538)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:479)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy34.save(Unknown Source)
My main class, App.java
public class App
{
public static void main(String[] args) {
ApplicationContext context =new AnnotationConfigApplicationContext(CassandraConfig.class);
CustomerRepo repo=context.getBean(CustomerRepo.class);
List<Customer> customers=new ArrayList<Customer>();
Customer cust=new Customer();
cust.SetId("142");
cust.setName("Mayor");
cust.setAcc_type("new");
cust.setAcc_name("savings");
cust.setSegment("Normal");
customers.add(cust);
Customer cust1 = new Customer();
cust1.SetId("143");
cust1.setName("Final");
cust1.setAcc_type("new");
cust1.setAcc_name("savings");
cust1.setSegment("Normal");
customers.add(cust1);
repo.save(customers);
}
}
The entity class, Customer.java
#Table(value="Customer")
public class Customer {
#PrimaryKeyColumn(name = "id",ordinal = 1,type = PrimaryKeyType.PARTITIONED)
private String id;
#Column(value ="name")
private String name;
#Column(value = "acc_name")
private String acc_name;
#Column(value = "acc_type")
private String acc_type;
#Column(value = "segment")
private String segment;
public Customer(String id, String name, String acc_name, String acc_type,
String segment) {
this.id=id;
this.name=name;
this.acc_name=acc_name;
this.acc_type=acc_type;
this.segment=segment;
}
public Customer() {
}
public void SetId(String id)
{
this.id=id;
}
public void setName(String name)
{
this.name=name;
}
public void setAcc_name(String acc_name)
{
this.acc_name=acc_name;
}
public void setAcc_type(String acc_type)
{
this.acc_type=acc_type;
}
public void setSegment(String segment)
{
this.segment=segment;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getAcc_name() {
return acc_name;
}
public String getAcc_type() {
return acc_type;
}
public String getSegment() {
return segment;
}
}
And finally, the repository, CustomerRepo.java
import com.Entity.Customer;
public interface CustomerRepo extends CassandraRepository<Customer> {
}
Is this an issue (I haven't been able to find via Goolge or the site), or am I missing some annotations ?
For batch queries, use CassandraTemplate helps to insert batch of operations with multiple entities. This is available with Spring Data Cassandra.
example code:
CassandraBatchOperations batchOps = cassandraTemplate.batchOps();
batchOps(movieByGenre);
batchOps(movieByActor);
batchOps.insert(movie);
batchOps.execute();
This will use Cassandra native Batch operation internally.

Static method call from Eclipse Plugin: InjectionException

I have 2 plugin projects - generator.ui and generator.core.
The generator.ui depends on generator.core plugin for processes and data manipulation. However wherever there is an API call on generator.core (through static method invocation), I get an exception mentioned below:
org.eclipse.e4.core.di.InjectionException: java.lang.NoClassDefFoundError: de/upb/crc901/serge/generator/Generator
at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:63)
at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:243)
at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:224)
at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132)
at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:167)
at org.eclipse.core.commands.Command.executeWithChecks(Command.java:499)
at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:508)
at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:213)
at org.eclipse.e4.ui.workbench.renderers.swt.HandledContributionItem.executeItem(HandledContributionItem.java:850).........
Caused by: java.lang.ClassNotFoundException: de.upb.crc901.serge.generator.Generator cannot be found by de.upb.crc901.serge.ui_1.0.0.qualifier
at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:501)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:421)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:412)
at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:107)
at java.lang.ClassLoader.loadClass(Unknown Source)
Now this NoClassDefFoundError always comes for the class which contains static method for object creation as the design pattern followed is "Singleton".
Any help would be greatly appreciated.
Here is the code, From the UI plugin; the configuration hub class:
public class ConfigurationHub implements IConfigurationHub {
private IGenerator generator;
private static IConfigurationHub configurationHub;
/*
* Constructor private to make Singleton
*/
private ConfigurationHub() {
generator = GeneratorFactory.createGenerator(Generator.class);
}
public static synchronized IConfigurationHub getInstance() {
if(null == configurationHub) {
configurationHub = new ConfigurationHub();
}
return configurationHub;
}
}
The GeneratorFactory class is in Generator plugin:
public class GeneratorFactory {
private GeneratorFactory() {}
public static <T extends IGenerator> T createGenerator(Class<T> type) {
try {
return (T) type.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
return null;
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
}
}
}
Regards,
Sid

How to set default value for double type field in JavascriptObject?

I have a JavaScriptObject like this:
#SingleJsoImpl(Test1Impl.class)
public interface Test1
{
double getValue();
void setValue(String Value);
}
public class Test1Impl extends JavaScriptObject implements Test1
{
protected Test1Impl()
{
}
#Override
public final native double getValue()/*-{
return this.Value||(this.Value=0);
}-*/;
#Override
public final native void setValue(String Value)/*-{
this.Value = Value;
}-*/;
}
And I want to use this:
return this.Value||(this.Value=0);
to set default value,but when I test it
public class GWT_Test implements EntryPoint{
public static native void log(Object message)/*-{
console.log(message);
}-*/;
#Override
public void onModuleLoad()
{
Test1 t1=(Test1) Test1Impl.createObject();
log(t1.getValue());
}
}
I got these erros:
com.google.gwt.core.client.JavaScriptException: (null) #com.gwt.test.client.GWT_Test::log(Ljava/lang/Object;)([Java object: java.lang.Double#239824989]): null
at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:249)
at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:576)
at com.google.gwt.dev.shell.ModuleSpace.invokeNativeVoid(ModuleSpace.java:304)
at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeVoid(JavaScriptHost.java:107)
at com.dsc.gwt.test.client.GWT_Test.log(GWT_Test.java)
at com.dsc.gwt.test.client.GWT_Test.onModuleLoad(GWT_Test.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.google.gwt.dev.shell.ModuleSpace.onLoad(ModuleSpace.java:411)
at com.google.gwt.dev.shell.OophmSessionHandler.loadModule(OophmSessionHandler.java:200)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:526)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:364)
at java.lang.Thread.run(Thread.java:744)
So what is the problem here? Or
How to set default value for double type field?
Update:
#Override
public void onModuleLoad()
{
Test1 t1=(Test1) Test1Impl.createObject();
printDouble(t1.getValue());
}
private void printDouble(Double num){
log(num.toString());
}
and this
#Override
public void onModuleLoad()
{
Test1 t1=(Test1) Test1Impl.createObject();
log(Double.toString(t1.getValue()));
}
Worked as I expected,and can anybody explain first line of error messages?
com.google.gwt.core.client.JavaScriptException: (null)#com.gwt.test.client.GWT_Test::log(Ljava/lang/Object;)([Java object: java.lang.Double#239824989]): null
The error you're seeing is the JS equivalent to a NullPointerException.
GWT runs in an iframe, an depending on browsers iframes don't always have a console object. Use $wnd.console to reference the console of the top window, where your widgets et al. live.