I try to develop some server program using spring4 and jackrabbit. When i test the Controller class using JUnit, BeanCreationExceptrion error is occurs. I think this error associated with autowired variable. help me. how to solve this problem?
This is head of my Controller class.
package kr.ac.jbnu.sql.soremore.controller;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.jcr.Node;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.ac.jbnu.sql.soremore.model.RDML;
import kr.ac.jbnu.sql.soremore.model.Traceability;
import kr.ac.jbnu.sql.soremore.service.IRDMLConverter;
import kr.ac.jbnu.sql.soremore.service.IRDMLDBMgmt;
import kr.ac.jbnu.sql.soremore.service.IRDMLRDFMgmt;
import kr.ac.jbnu.sql.soremore.service.RDMLDBException;
import kr.ac.jbnu.sql.soremore.service.RDMLRDFException;
import kr.ac.jbnu.sql.soremore.service.RevisionControlException;
import kr.ac.jbnu.sql.soremore.service.rdf.RDFConverter;
import org.apache.log4j.Logger;
import org.jdom2.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
// reference
// http://crunchify.com/simplest-spring-mvc-hello-world-example-tutorial-spring-model-view-controller-tips/
#Controller
public class SoremoreController {
private static final int buffer_size = 1024;
static Logger logger = Logger.getLogger(SoremoreController.class.getName());
private static String fileName = "";
#Autowired
private ApplicationContext appContext = null;
#Autowired
private IRDMLConverter rdmlConverter = null;
#Autowired
private IRDMLRDFMgmt rdmlRDFMgmt = null;
#Autowired
private IRDMLDBMgmt rdmlDBMgmt = null;
#Autowired
private RDFConverter rdfConverter = null;
....
This is my test class.
package kr.ac.jbnu.sql.soremore.controller;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import kr.ac.jbnu.sql.soremore.model.RDML;
import kr.ac.jbnu.sql.soremore.model.Traceability;
import kr.ac.jbnu.sql.soremore.service.RDMLDBException;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
#RunWith(SpringJUnit4ClassRunner.class)
//#ContextConfiguration(locations = { "classpath:/soremore-servlet.xml" })
#ContextConfiguration(locations = { "/application-config.xml" })
public class SoremoreControllerTest {
#Autowired
SoremoreController soremoreController = null;
#Test
public void storeRDML() {
// String[] hwpmlPaths = { "resource/sample_rdml/예제 1.xml",
// "resource/sample_rdml/예제 2.xml",
// "resource/sample_rdml/예제 3.xml",
// "resource/sample_rdml/예제 4.xml",
// "resource/sample_rdml/예제 5.xml",
// "resource/sample_rdml/예제 6.xml",
// "resource/sample_rdml/예제 7.xml",
// "resource/sample_rdml/예제 8.xml",
// "resource/sample_rdml/예제 9.xml",
// "resource/sample_rdml/예제 10.xml" };
//
// for (String hwpmlPath : hwpmlPaths) {
// soremoreController.storeRDML(hwpmlPath);
// }
ArrayList<RDML> rdmls = loadTestRDML();
boolean isSuccessful = false;
for (RDML rdml : rdmls) {
try {
soremoreController.storeRDML(rdml);
System.out.println();
isSuccessful = true;
} catch (Exception e) {
e.printStackTrace();
isSuccessful = false;
}
}
Assert.assertTrue(isSuccessful);
}
#Test
public void storeRDMLWithTraceability() throws IOException {
List<RDML>rdmls = null ;
String previousRDMLId = "xxx";
for (RDML rdml : rdmls) {
soremoreController.storeRDMLWithTraceability(rdml,
previousRDMLId, TraceabilityTypes.satisfy);
}
}
#Test
public void updateRDMLWithTraceability() {
String previousRDMLId1 = "xxx";
String previousRDMLId2 = "xxx";
String updatedTraceability = soremoreController.updateRDMLTraceability(
previousRDMLId1, previousRDMLId2, TraceabilityTypes.satisfy);
}
#Test
public void deleteRDMLWithTraceability() {
String previousRDMLId1 = "xxx";
String previousRDMLId2 = "xxx";
String removedTraceability = soremoreController.deleteRDMLTraceability(
previousRDMLId1, previousRDMLId2);
}
#Test
public void searchRDML() {
String rdmlKeyWord = "abc";
ArrayList<RDML> rdmls = soremoreController.searchRDML(rdmlKeyWord);
for (RDML rdml : rdmls) {
System.out.println(rdml);
}
}
#Test
public void searchRDML0() {
String rdmlKeyWord = "def";
ArrayList<RDML> rdmls = soremoreController.searchRDML(rdmlKeyWord);
for (RDML rdml : rdmls) {
System.out.println(rdml);
}
}
#Test
public void searchRDML1() {
String rdmlKeyWord = "2차년도계획서";
ArrayList<RDML> rdmls = soremoreController.searchRDML(rdmlKeyWord);
for (RDML rdml : rdmls) {
System.out.println(rdml);
}
}
#Test
public void getRDML() {
String rdmlID = "abc";
RDML rdml = soremoreController.getRDML(rdmlID);
}
#Test
public void getParentIDs() {
String rdmlID = "abcd";
ArrayList<String> parentIDs = soremoreController.getParentIDs(rdmlID);
for (String string : parentIDs) {
}
}
#Test
public void getChildIDs() {
String rdmlID = "abcd";
ArrayList<String> childIDs = soremoreController.getChildIDs(rdmlID);
for (String string : childIDs) {
}
}
public void getDirectLinkedTraceability() {
String rdmlID = "abcd";
ArrayList<Traceability> linkedTraceabilities = soremoreController
.getDirectLinkedTraceability(rdmlID);
for (Traceability traceability : linkedTraceabilities) {
}
}
public ArrayList<RDML> loadTestRDML() {
ArrayList<RDML> rdmls = new ArrayList<RDML>();
String xmlSource = "resource/sample_rdml";
File sourceDir = new File(xmlSource);
File[] sourceFiles = sourceDir.listFiles();
for (File file : sourceFiles) {
RDML rdml = new RDML();
rdml.setRdmlAsDocument(createDocument(file));
rdmls.add(rdml);
}
return rdmls;
}
private Document createDocument(File rdmlPathAsFile) {
SAXBuilder jdomBuilder = new SAXBuilder();
Document jdomDocument = null;
try {
jdomDocument = jdomBuilder.build(rdmlPathAsFile);
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jdomDocument;
}
}
This is my spring configuration xml file.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="kr.ac.jbnu.sql.soremore" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
<property name="contentType" value="text/html; charset=UTF-8" />
</bean>
<!-- for file upload -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- setting maximum upload size -->
<property name="maxUploadSize" value="20000000" />
</bean>
</beans>
This is head of class of one variable.
package kr.ac.jbnu.sql.soremore.service.rdml;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.jcr.UnsupportedRepositoryOperationException;
import javax.jcr.ValueFormatException;
import javax.jcr.lock.LockException;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.NoSuchNodeTypeException;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import javax.jcr.version.Version;
import javax.jcr.version.VersionException;
import javax.jcr.version.VersionHistory;
import javax.jcr.version.VersionIterator;
import javax.jcr.version.VersionManager;
import javax.xml.parsers.ParserConfigurationException;
import kr.ac.jbnu.sql.soremore.controller.SoremoreController;
import kr.ac.jbnu.sql.soremore.model.RDML;
import kr.ac.jbnu.sql.soremore.service.IRDMLDBMgmt;
import kr.ac.jbnu.sql.soremore.service.RDMLDBException;
import kr.ac.jbnu.sql.soremore.service.RevisionControlException;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.log4j.Logger;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.XMLOutputter;
import org.springframework.stereotype.Service;
#Service
public class RDMLDBMgmtImpl implements IRDMLDBMgmt {
static Logger logger = Logger.getLogger(SoremoreController.class.getName());
static private int docNumber = 0;
private Repository repository;
private Session session;
....
This is stacktrace.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'kr.ac.jbnu.sql.soremore.controller.SoremoreControllerTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: kr.ac.jbnu.sql.soremore.controller.SoremoreController kr.ac.jbnu.sql.soremore.controller.SoremoreControllerTest.soremoreController; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [kr.ac.jbnu.sql.soremore.controller.SoremoreController] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1204)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:385)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:82)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:212)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:199)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:251)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:253)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:216)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:82)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:60)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:67)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:162)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: kr.ac.jbnu.sql.soremore.controller.SoremoreController kr.ac.jbnu.sql.soremore.controller.SoremoreControllerTest.soremoreController; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [kr.ac.jbnu.sql.soremore.controller.SoremoreController] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:555)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 26 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [kr.ac.jbnu.sql.soremore.controller.SoremoreController] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1261)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1009)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:904)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:527)
... 28 more
In order for Spring to autowire the SoremoreController field in your test case it needs a bean definition in the ApplicationContext for a bean of that type. That means you need to component-scan the package (or a parent package) where the SoremoreController is defined in the xml file you point out in the ContextConfiguration annotation.
Note that all autowired fields in SoremoreController instance must also have corresponding beans defined in the ApplicationContext, otherwise Spring will not be able to create that instance, causing your test to fail with stacktraces similar to the one you posted (but always explicitly pointing out - towards the end - the root cause of the problem).
Related
I have expanda.js. I am calling this dao in my formcontroller.java file but I get the following error.
I guess I need to define DAO as a bean. How can I do this in the SpringWebConfig.java file?
I do not have much control over spring, sorry
Console Error:
SEVERE: Allocate exception for servlet [dispatcher]
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.esma.dao.ExpDao' available: expected
at least 1 bean which qualifies as autowire candidate. Dependency
annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1777)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1333)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1287)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:130)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1415)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:608)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:531)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:925)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:588)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:702)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:578)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:530)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:170)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1134)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:777)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:830)
ExpDao.java
package com.esma.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.esma.model.Expense;
public class ExpDao {
JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public int save(Expense exp){
String sql="insert into Emp99(name,salary,designation) values('"+exp.getExpenseType()+"',"+exp.getQuantity()+","+exp.getPrice()+","+exp.getPaymentDate()+",'"+exp.getNote()+"' )";
return template.update(sql);
}
public List<Expense> getExpenses(){
return template.query("select * from expenses",new RowMapper<Expense>(){
public Expense mapRow(ResultSet result, int row) throws SQLException {
Expense e=new Expense();
e.setExpenseType(result.getString(2));
e.setQuantity(result.getInt(3));
e.setPrice(result.getInt(4));
e.setPaymentDate(result.getDate(5));
e.setNote(result.getString(6));
return e;
}
});
}
}
SpringRootConfig.js
package com.esma.config;
import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#ComponentScan(basePackages ={"com.esma.dao"})
public class SpringRootConfig {
//TODO: Services, DAO, DataSource, Email Sender or some other business layer beans.
// In production the datasource configuration is done in properties file but for simplicity purpose it is hardcoded here.
#Bean
public BasicDataSource getDataSource(){
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/apartmentmanagement");
ds.setUsername("root");
ds.setPassword("1234");
ds.setMaxTotal(2);
ds.setInitialSize(1);
ds.setTestOnBorrow(true);
ds.setValidationQuery("SELECT 1");
ds.setDefaultAutoCommit(true);
return ds;
}
}
SpringWebConfig.js
/**
*
*/
package com.esma.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import com.esma.dao.ExpDao;
import com.esma.model.Expense;
#Configuration
#ComponentScan(basePackages = { "com.esma" })
#EnableWebMvc
public class SpringWebConfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// TODO Auto-generated method stub
System.out.println("Inside Resource Handler");
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
}
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver vr = new InternalResourceViewResolver();
vr.setViewClass(JstlView.class);
vr.setPrefix("/WEB-INF/view/");
vr.setSuffix(".jsp");
return vr;
}
#Bean
public ExpDao expenceDao() {
ExpDao exp = new ExpDao();
exp.setTemplate(com.esma.dao.ExpDao.class);
return exp;
}
}
FormController.js
package com.esma.controller;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.esma.dao.ExpDao;
import com.esma.model.Expense;
#Controller
public class FormController {
#Autowired
ExpDao dao;
#RequestMapping(value = "/form", method = RequestMethod.GET)
public String form() {
new ModelAndView("expense", "expenseObject", new Expense());
return "expenseForm";// JSP form view
}
#RequestMapping(value = "/expense/save", method = RequestMethod.POST)
public String addExpense(#ModelAttribute("expenseObject") Expense expense, ModelMap model) {
dao.save(expense);
model.addAttribute("expenseType", expense.getExpenseType());
model.addAttribute("quantity", expense.getQuantity());
model.addAttribute("price", expense.getPrice());
model.addAttribute("paymentDate", expense.getPaymentDate());
model.addAttribute("note", expense.getNote());
System.out.println(model.getAttribute("expenseType"));
System.out.println(model.getAttribute("quantity"));
System.out.println(model.getAttribute("price"));
System.out.println(model.getAttribute("paymentDate"));
System.out.println(model.getAttribute("note"));
return "result";
}
#RequestMapping(value = "/list")
public String expenseList(Model m) {
List<Expense> list = dao.getExpenses();
m.addAttribute("list", list);
System.out.println("expense");
return "expenseList";// JSP form view
}
}
Hello Esma and welcome to stackoverflow.
Since you declared explecitely your bean of type ExpDao with #Bean annotation in the SpringWebConfig.js, The bean registred in the spring context is expenceDao which is the same method name in this code section:
#Bean
public ExpDao expenceDao() {
ExpDao exp = new ExpDao();
exp.setTemplate(com.esma.dao.ExpDao.class);
return exp;
}
So Spring container will create and register a bean of type ExpDao with name (or id ) expenceDao (which is the name of the method expenceDao()
and then you ask spring with this section of code to inject a bean with name expDao which is not found.
#Controller
public class FormController {
#Autowired
ExpDao dao;
// the rest of the code
}
So spring will return a NoSuchBeanDefinitionException because it didn't found a bean with name expDao.
In order to work, you can just change the method name expenceDao() to expDao() in SpringWebConfig.java file in order that spring create the bean with name expDao and not expenceDao.
Thanks.
I want to add an upload function to my spring boot application;
this is my upload Rest Controller
package org.sid.web;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.sid.entities.FileInfo;
#RestController
public class UploadController {
#Autowired
ServletContext context;
#RequestMapping(value = "/fileupload/file", headers = ("content-type=multipart/*"), method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<FileInfo> upload(#RequestParam("file") MultipartFile inputFile) {
FileInfo fileInfo = new FileInfo();
HttpHeaders headers = new HttpHeaders();
if (!inputFile.isEmpty()) {
try {
String originalFilename = inputFile.getOriginalFilename();
File destinationFile = new File(
context.getRealPath("C:/Users/kamel/workspace/credit_app/uploaded") + File.separator + originalFilename);
inputFile.transferTo(destinationFile);
fileInfo.setFileName(destinationFile.getPath());
fileInfo.setFileSize(inputFile.getSize());
headers.add("File Uploaded Successfully - ", originalFilename);
return new ResponseEntity<FileInfo>(fileInfo, headers, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<FileInfo>(HttpStatus.BAD_REQUEST);
}
} else {
return new ResponseEntity<FileInfo>(HttpStatus.BAD_REQUEST);
}
}
}
but when testing this in postman with inserting http://localhost:8082/fileupload/file and adding a file to the body
i got this error: "exception": org.springframework.web.multipart.support.MissingServletRequestPartException",
"message": "Required request part 'file' is not present,
This is how your request in Postman should look like:
My sample code:
application.properties
#max file and request size
spring.http.multipart.max-file-size=10MB
spring.http.multipart.max-request-size=11MB
Main Application Class:
Application.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Rest controller class:
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
#Controller
#RequestMapping("/fileupload")
public class MyRestController {
#RequestMapping(value = "/file", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody String myService(#RequestParam("file") MultipartFile file,
#RequestParam("id") String id) throws Exception {
if (!file.isEmpty()) {
//your logic
}
return "some json";
}
}
pom.xml
//...
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
....
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
//...
In your method you have specified like this
#RequestParam("file"). Hence it is expecting the key to be file. It is quite evident in the exception message. Use this name in the Key field in Postman when you upload file.
More information here integration test case and file upload
I also had similar issue and was getting the error request part file not present.
But I later realized that I have this code in my application which was causing problem:
#Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new
CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(1000000000);
return multipartResolver;
}
I removed this and it started working for both RequestPart and RequestParam.
See the related issue below:
https://forum.predix.io/questions/22163/multipartfile-parameter-is-not-present-error.html
Except for other posted answers, the problem might be realated to missing multipart support for the servlet handling the request (spring's DispatcherServlet in case of Spring's app).
This can be fixed by adding multipart support to dispatcher servlet in web.xml declaration or during initialization (in case of annotation-based config)
a) web-xml based config
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/dispatcher-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<multipart-config>
<max-file-size>10485760</max-file-size>
<max-request-size>20971520</max-request-size>
<file-size-threshold>5242880</file-size-threshold>
</multipart-config>
</servlet>
</web-app>
b) for annotation-based configuration this would be following:
public class AppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) {
final AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
final ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcher", new DispatcherServlet(appContext));
registration.setLoadOnStartup(1);
registration.addMapping("/");
File uploadDirectory = new File(System.getProperty("java.io.tmpdir"));
MultipartConfigElement multipartConfigElement = new MultipartConfigElement(uploadDirectory.getAbsolutePath(), 100000, 100000 * 2, 100000 / 2);
registration.setMultipartConfig(multipartConfigElement);
} }
Then we need to provide multipart resolver which can resolve files sent as multipart-request. For annotation config this can be done in following way:
#Configuration
public class MyConfig {
#Bean
public MultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
}
For xml-based spring configuration you need to add this bean to the context via tag declaration declaration:
<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver" />
Alternatively to spring's standard multipart resolver you can use implementation from commons. This way however extra dependency is required:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000000"/>
</bean>
I had similar issue with error Could not resolve parameter [0] in public org.springframework.http.ResponseEntity... Required request part 'file' is not present and tried many things but one change resolved this issue.
Had to update
// old
#RequestParam("file") MultipartFile inputFile
// new
#RequestParam(value = "file") MultipartFile inputFile
In my case, i have multi module project as;
core > api > admin
Admin and api are parent of core module.
Core/ImageController:
#RequestMapping(value = "/upload/image", method = RequestMethod.POST)
public ResponseEntity uploadBanner(#RequestParam(value = "file", required =
false) MultipartFile bannerFile){...}
AdminApplicationInitializer:
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(AdminApplicationInitializer.class);
}
#Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
//100MB
resolver.setMaxUploadSize(100 * (long) 1024 * 1024);
return resolver;
}
#Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
factory.setMaxFileSize(DataSize.ofMegabytes(200L));
factory.setMaxRequestSize(DataSize.ofMegabytes(200L));
return factory.createMultipartConfig();
}
When i tried to upload file from api module with core service "/upload/image".
I had get an error : "Required request part 'file' is not present".
Cause of ApiInitializer had not configuration like AdminInitializer.
The Solution : i added multipartResolver() and multipartConfigElement() method to ApiApplicationInitializer.Then it worked.
I have a problem... Well, when I start my test, I throw me the following error, and can not find that he is doing wrong. Agrege corresponding to the "Application-context" where is the notation hibernate settings, but I can not perform my test successfully
"WebAppInitializer":
package com.checkwork.conf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
public class WebAppInitializer implements WebApplicationInitializer {
private static final Logger logger = LoggerFactory.getLogger(WebAppInitializer.class);
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
logger.info("Initializing web application with context configuration class {}", WebAppConfigurer.class.getCanonicalName());
//WebApplication Param-Value (Web.XML)
AnnotationConfigWebApplicationContext webAppContext = new AnnotationConfigWebApplicationContext();
webAppContext.register(WebAppConfigurer.class);
//Crea Servlet y mapea las peticiones con "/" sin extensiones.
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher",
new DispatcherServlet(webAppContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
"WebAppConfigurer":
package com.checkwork.conf;
import com.checkwork.model.Empleado;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#Configuration
#EnableTransactionManagement /** Gestor de transacciones que permiten habilitar los componentes para la conexion a la BD */
#EnableWebMvc
#ComponentScan(basePackages = {"com.checkwork"})
public class WebAppConfigurer extends WebMvcConfigurerAdapter {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean(name = "dataSource")
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/module");
dataSource.setUsername("root");
dataSource.setPassword("root");
return dataSource;
}
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
return properties;
}
#Autowired
#Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
sessionBuilder.addProperties(getHibernateProperties());
sessionBuilder.addAnnotatedClasses(Empleado.class);
return sessionBuilder.buildSessionFactory();
}
#Autowired
#Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(
SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager(
sessionFactory);
return transactionManager;
}
/**
* Agrega al Caché la librería OpenUI5 en tiempo de ejecución {WEB-INF/lib}
*/
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/", "/resources/**")
.setCachePeriod(31556926);
}
}
Test:
package com.checkwork.service;
import static org.junit.Assert.*;
import javax.transaction.Transactional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.checkwork.conf.WebAppConfigurer;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = WebAppConfigurer.class)
public class EmpleadoServiceTest {
private EmpleadoService empleadoService;
#Before
public void setUp() throws Exception{
empleadoService = new EmpleadoService();
}
#Test
#Transactional
public void getAllTest(){
assertNotNull(empleadoService.getAll());
}
}
Error console - Junit:
SEVERE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#1761de10] to prepare test instance [com.checkwork.service.EmpleadoServiceTest#22df874e]
java.lang.IllegalStateException: Failed to load ApplicationContext...
Change
#ContextConfiguration(classes = WebAppConfigurer.class)
to
#ContextConfiguration(classes = WebAppConfigurer.class, initializers=WebAppInitializer.class)
update
Also include #WebIntegrationTest below #ContextConfiguration
I'm new to spring and dbunit and have problem with testing my dao layer. The entry is inserted succsessfully, but test ends with failure. Could you help me, please?
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import com.epam.lab.marharytakhramtsova.javalab.task1.dao.TagDAO;
import com.epam.lab.marharytakhramtsova.javalab.task1.dto.Tag;
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.github.springtestdbunit.annotation.ExpectedDatabase;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "/spring-config.xml" })
#TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class,
DbUnitTestExecutionListener.class })
public class TestTagDAO {
#Autowired
private TagDAO tagDAO;
#Test
#DatabaseSetup(value = "/TagDAOTest.xml")
#ExpectedDatabase(value= "/expectedData.xml")
public void testInsert() throws Exception {
Tag tagToInsert = new Tag(4, "insertedTag");
tagDAO.insert(tagToInsert);
}
}
TagDAOTest.xml
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
<tag tag_id = "3" tag_name="myTag3" />
</dataset>
expectedData.xml
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
<tag tag_id = "3" tag_name="myTag3" />
<tag tag_id = "4" tag_name="insertedTag" />
</dataset>
Here is failure trace
I would be very grateful for the help!
Try this
#Test
#DatabaseSetup(value = "/TagDAOTest.xml")
#ExpectedDatabase(assertionMode=DatabaseAssertionMode.NON_STRICT, value= "/expectedData.xml")
public void testInsert() throws Exception {
Tag tagToInsert = new Tag(4, "insertedTag");
tagDAO.insert(tagToInsert);
}
I'm using spring-mvc version 4.1.6-RELEASE with Junit 4.12 and java 1.7, I have a controller for file uploading who works when I've tested it on server with Browser. But when I try to test it with junit the mockfilemultipart is always empty and I'm sure isn't so in the test class.
This is my servlet-context.xml
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- beans:import resource="../controller-context.xml"/-->
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
<context:component-scan base-package="it.isfol.iweb" />
This is the controller
package it.isfol.iweb.controller.pianoattivita;
import it.isfol.iweb.bean.wrappers.PianoAttivitaWrapper;
import it.isfol.iweb.controller.common.IsfolController;
import it.isfol.iweb.exceptions.IWebFatalException;
import it.isfol.iweb.service.pianoattivita.FilePianoAttivitaService;
import it.isfol.iweb.util.SessionConstant;
import java.util.Arrays;
import java.util.Collection;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
#Controller
public class UploadPianoAttivitaController extends IsfolController {
/**
*
*/
private static final long serialVersionUID = 5455170192118107020L;
private static final String UPLOAD_PAGE = "upload/upload";
private final Logger logger = LoggerFactory.getLogger(UploadPianoAttivitaController.class);
#Autowired
private FilePianoAttivitaService filePianoAttivitaService;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String uploadHomePage(HttpSession session) {
logger.info("I'm home");
return goToUploadPage(session);
}
#RequestMapping(value = "/uploadInit", method = RequestMethod.GET)
public String uploadPageRedirect(HttpSession session) {
logger.info("redirect into upload");
return goToUploadPage(session);
}
#RequestMapping(value = "/uploadPiano", method = RequestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE)
#ResponseBody
public String upload(#RequestParam("files[]") MultipartFile[] files, HttpSession session) throws IWebFatalException {
logger.debug("Writing file to disk...");
try {
Collection<PianoAttivitaWrapper> piani = filePianoAttivitaService.getPianoAttivitaWrapperFromFiles(Arrays.asList(files), session.getId());
session.setAttribute(SessionConstant.PIANO_ATTIVITA_LIST_WRAPPER, piani);
} catch (IWebFatalException e) {
throw e;
} catch (Throwable t) {
logger.error(t.getLocalizedMessage(), t);
throw new IWebFatalException(t);
}
return "pianoAttivita";
}
private String goToUploadPage(HttpSession session) {
logger.debug("redirect on upload page");
sessionHelper.clearSessionPianoReference(session);
return UPLOAD_PAGE;
}
public void setFilePianoAttivitaService(FilePianoAttivitaService filePianoAttivitaService) {
this.filePianoAttivitaService = filePianoAttivitaService;
}
}
Then my abstract class for testing
package it.isfol.iweb;
import java.io.IOException;
import java.util.Properties;
import org.junit.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
#WebAppConfiguration(value = "src/main/webapp")
#ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring/root-context.xml", "file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml" })
public abstract class IsfolIwebTester extends AbstractJUnit4SpringContextTests {
private final Logger logger = LoggerFactory.getLogger(IsfolIwebTester.class);
private Properties testProperties = new Properties();
#Autowired
private WebApplicationContext webapp;
protected MockMvc mockMvc;
#Before
public void setup() {
logger.debug("reading properties");
try {
testProperties.load(this.getClass().getResourceAsStream("/test-conf.properties"));
this.mockMvc = MockMvcBuilders.webAppContextSetup(webapp).build();
} catch (IOException e) {
logger.error(e.getMessage(), e);
} catch (Throwable e) {
logger.error(e.getLocalizedMessage(), e);
}
}
public String getProperty(String key) {
return testProperties.getProperty(key);
}
}
and finally the test class who extends the class above
package it.isfol.iweb.pianoattivita;
import it.isfol.iweb.IsfolIwebTester;
import org.apache.commons.io.FilenameUtils;
import org.apache.tika.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
public class FilePianoAttivitaTester extends IsfolIwebTester {
private final Logger logger = LoggerFactory.getLogger(FilePianoAttivitaTester.class);
#Test
public void testRunning() {
logger.debug("Test started");
try {
String originalFile = getProperty("test.file.pianoattivita.path");
String originalName = FilenameUtils.getName(originalFile);
byte[] content = IOUtils.toByteArray(getClass().getResourceAsStream(originalFile));
MockMultipartFile file = new MockMultipartFile("testJunit", originalName, null, content);
this.mockMvc.perform(MockMvcRequestBuilders.fileUpload("/uploadPiano").file(file)).andExpect(MockMvcResultMatchers.status().isOk()).andReturn().equals("pianoAttivita");
this.mockMvc.perform(MockMvcRequestBuilders.get("/pianoAttivita")).andExpect(MockMvcResultMatchers.view().name("upload/upload"));
} catch(Throwable t) {
logger.error(t.getLocalizedMessage(), t);
Assert.fail();
}
}
}
In the method upload of UploadPianoAttivitaController when I run Junit the param files[] contain 1 empty MultiPartFile, while when I run it on server and I upload a file from page everything is ok.
The name of your RequestParam for files must match with the MockMultipartFile name.
In your case is "files []" and in the mock is "testJunit", you can watch your HttpServletRequest params in your controller.
Try this way:
MockMultipartFile mockMultipartFile = new MockMultipartFile("file",
"OriginalName.txt",
"text/plain",
rateExceptionsFile);
mockMvc.perform(multipart(BASE_PATH + "/uploadFile")
.file(mockMultipartFile)
.contentType(MediaType.MULTIPART_FORM_DATA))
.andExpect(status().isOk());