java.lang.AssertionError: Status expected:<200> but was:<404> - java

I know there are so many similar posts for this question. I tried to implement all but not working for me. Please help me why I am getting this error java.lang.AssertionError: Status expected:<200> but was:<404>
I tried to implement MediaType.APPLICATION_JSON
Annotation #EnableWebMvc
But not working
Do I need to include headers also to get that working? Please let me know
Code that I have written is:
Controller class:
#EnableWebMvc
#Controller
public class Controller {
#RequestMapping(value = "/app/data", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseData> DataInquiry(
#RequestBody RequestData requestData,
#RequestHeader(value = Constants.ID, required = false) String transactionId) {
//Do some action
return new ResponseEntity<ResponseData>(responseData, headers, HttpStatus.OK);
}
ControllerTest class:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration({"classpath*:spring/beanRefContext.xml"})
#WebAppConfiguration
public class ControllerTest{
public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(),
Charset.forName("utf8"));
private MockMvc mockMvc;
#Autowired
WebApplicationContext wac;
ObjectMapper mapper;
AnnotationMethodHandlerAdapter adapter;
MockHttpServletRequest request;
MockHttpServletResponse response;
#Before
public void setUp() {
System.out.println("Before method execution in CommonInquiryControllerTest class ");
//this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();
adapter = new AnnotationMethodHandlerAdapter();
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
mapper = new ObjectMapper();
}
#Test
public void InquiryDataTest() throws Exception, JsonProcessingException
{
RequestData anObject = new RequestData();
anObject.setId("1234");
anObject.setQualifier("someData");
mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
String requestJson=ow.writeValueAsString(anObject );
assertNotNull(anObject.getId());
assertNotNull(anObject.getQualifier());
ResultActions resultActions = mockMvc
.perform(post("/app/data")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.content(mapper.writeValueAsBytes(requestJson)));
resultActions.andExpect(status().isOk());
//This will print the response JSON string
resultActions.andDo(MockMvcResultHandlers.print());
Assert.assertEquals(200, response.getStatus());
}
xml Info:
beanContext.xml
<?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:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:encryption="http://www.jasypt.org/schema/encryption"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.jasypt.org/schema/encryption
http://www.jasypt.org/schema/encryption/jasypt-spring3-encryption-1.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<import resource="classpath:core-application-context.xml"/>
<import resource="classpath:region-context.xml"/>
<jee:jndi-lookup id="somedataSourceid" jndi-name="some name" proxy-interface="javax.sql.DataSource"/>
<!-- enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven/>
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<!-- a PlatformTransactionManager is still required -->
<bean id="transactionManager" class="org.springframework.transaction.jta.WebSphereUowTransactionManager"/>
</beans>
In region-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans default-lazy-init="true" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="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
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">
<!-- Import this context file and pass it the requisite properties and a Data Source named dataSource -->
<context:component-scan base-package="com.java.geek"/>
</beans>

Even though you Enable WebMvc, you need to scan your controller to auto register controller & url mappings.component-scan scans packages to find and register beans within the application context.
<context:component-scan base-package="com.mycompany.xyz" />
I doubt component scanning is missing in your context xml.If so Add this statement in your beanRefContext.xml.

Related

Spring Cloud Gateway injection in Unit Tests is not Working

I have a Global Filter with an injected attribute.
public class AuthenticationGlobalFilter implements GlobalFilter, Ordered {
#Autowired
private Permission permission;
#Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
long serviceId = 0;
try {
ServerHttpRequest request = exchange.getRequest();
HttpHeaders headers = request.getHeaders();
String fromKey = headers.getFirst("x-api-key");
String fromIp = headers.getFirst("x-forwarded-for");
String fromSubject = headers.getFirst("******");
URI rqUrl = request.getURI();
String path = rqUrl.getPath();
serviceId = Long.parseLong(path.split("/")[6]);
permission.check(permission.identity(fromKey, fromSubject, fromIp), serviceId);
return chain.filter(exchange);
} catch (PermissionException e) {
exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
} catch (IllegalArgumentException e) {
exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
} catch (Exception e) {
exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
}
return Mono.empty();
}
}
Injection works perfectly when I run the application
#EnableDiscoveryClient
#SpringBootApplication
#EnableConfigurationProperties(ApiGatewayProperties.class)
#Import({ PermitAllSecurityConfiguration.class, CustomAttributesConfiguration.class })
#ImportResource(value = { "classpath:datasource.xml", "classpath:api-gateway-unico-beans.xml" })
public class ApiGatewayUnicoApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayUnicoApplication.class, args);
}
}
With this configuration 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:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<cache:annotation-driven
cache-manager="cacheManager" />
<context:annotation-config />
<context:component-scan
base-package="*****.apigatewayunico" />
<bean
class="*****.apigatewayunico.filters.AuthenticationGlobalFilter" />
<bean class="*****.apigatewayunico.Persistence"
p:sql="SELECT rep.url FROM RestService rs, RestEndpoint rep WHERE rep.id = rs.endpoint_id AND rs.id = ? AND rs.available = true" />
<bean id="permission"
class=*****.permission.Permission" />
The problem is that when I make a unit test, the property is injected in the unit test by not in the filter being tested, giving me errors about not being able to locate a bean that can satisfy this dependency.
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = RANDOM_PORT)
#DirtiesContext
public class AuthenticationGlobalFilterIntegrationTests extends BaseWebClientTests {
#Autowired
private Permission permission;
#Before
public void setup() {
super.setup();
reset(permission);
permission.check(null, 123456L);
}
#Test
public void runSucessTest() {
expectLastCall();
replay(permission);
testClient.get().uri("/status/200").exchange().expectStatus().isEqualTo(HttpStatus.OK);
}
#Test
public void runPermissionExceptionTest() throws Exception {
expectLastCall().andThrow(new PermissionException(""));
replay(permission);
testClient.get().uri("/status/200").exchange().expectStatus().isEqualTo(HttpStatus.FORBIDDEN);
}
#EnableAutoConfiguration
#SpringBootConfiguration
#Import(DefaultTestConfig.class)
#ImportResource(value = "classpath:authentication-filter-test-beans.xml")
public static class TestConfig {
}
}
authentication-filter-test-beans.xml:
<?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:c="http://www.springframework.org/schema/c"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:api-gateway-unico-test-beans.xml" />
<bean id="authenticationFilter"
class="*****.apigatewayunico.filters.AuthenticationGlobalFilter">
</bean>
</beans>
api-gateway-unico-test-beans.xml:
<?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:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
default-lazy-init="false">
<bean id="mockSupport" class="org.easymock.EasyMockSupport" />
<bean id="pp" factory-bean="mockSupport"
factory-method="createNiceMock"
c:_0="*****.permission.PermissionPersistence" />
<bean id="permission" factory-bean="mockSupport"
factory-method="createNiceMock"
c:_0="*****.permission.Permission" />
<bean id="jdbc" factory-bean="mockSupport"
factory-method="createNiceMock"
c:_0="org.springframework.jdbc.core.JdbcTemplate" />
<bean id="descoveryClienteMock" factory-bean="mockSupport"
factory-method="createNiceMock"
c:_0="org.springframework.cloud.client.discovery.DiscoveryClient" />
<bean id="serviceInstanceMock" factory-bean="mockSupport"
factory-method="createNiceMock"
c:_0="org.springframework.cloud.client.ServiceInstance" />
</beans>
Now when I try to add the unit test's configuration xml to the #ConextConfiguration annotation in the unit test, I get a test related to Reactor dependencies!
org.springframework.context.ApplicationContextException: Unable to
start reactive web server
Solved by annotating the dependency with #Lazy

Generate XML response in Spring MVC

I have a controller class, I'm expecting it to display the .xml response of model class which is annotated with #XmlRootElement. The Controller class method which displays all the student list is ,
#RequestMapping("studentlist")
public #ResponseBody
StudentList getStudentList() {
List<student> studentList = new ArrayList<student>();
studentList.add(new Student(3, "Robert", "Parera", "robert#gmail.com", "88"));
studentList.add(new Student(93, "Andrew", "Strauss","andrew#gmail.com", "89"));
studentList.add(new Student(239, "Eddy", "Knight", "knight#gmail.com", "79"));
return new StudentList(studentList);
}
}
i have added the #ResponseBody ,but still the class is not displaying the .xml response This is my web.xml.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.javasample.common.controller" />
<mvc:annotation-driven />
</beans>
Please advice what is missing. I also have model class which is properly annotated with #XMLElement ,#XmlRootElement etc. Kindly advice as I'm new to Spring MVC.

how to access property file value in the method of a class in spring

I am using spring 4.0.3.RELEASE
Here is my applicationContext.xml where i am configuring PropertyPlaceHolder
<?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:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="org.graphsearch.tutor.service.impls, org.graphsearch.tutor.dao.impls, org.graphsearch.tutor.configs, org.graphsearch.tutor.utils"/>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/properties/database/jdbc.properties</value>
<value>/WEB-INF/properties/alert/message.properties</value>
<value>/WEB-INF/properties/email/mail.properties</value>
<value>/WEB-INF/properties/logger/logging.properties</value>
</list>
</property>
</bean>
</beans>
In Email client class i am injecting property values like this
#Component
public class EmailClient {
#Value("${tutor.mail.common.note}")
private static String NOTE;
#Value("${tutor.mail.common.regards}")
private static String REGARDS;
#Value("${tutor.mail.from}")
private static String FROM;
#Autowired
private MailSender mailSender;
#Autowired
private Environment env;
public void sendRegisterMail(User user){
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(user.getEmailID());
String subject = env.getProperty("tutor.register.success.mail.subject"); //retuns null
String contentTemplate = env.getProperty("tutor.register.success.mail.content"); //returns null
MessageFormat format = new MessageFormat(contentTemplate);
Object[] args = {user.getFullName()};
StringBuffer content = new StringBuffer();
content.append(format.format(args));
content.append(NOTE);
content.append(REGARDS);
message.setSubject(subject);
message.setText(content.toString());
mailSender.send(message);
}
}
Now problem is #Value("${property.key}") does work like charm when i inject a private field of the class like NOTE, REGARDS, FROM.
But if i need this value inside the method sendRegisterMail()
#Value("$key") is giving compiler error. I searched on web few examples are there getting properties value through environment so i used like i have done in EmailClient class but it always give me null. I checked the log it says it can not find the property key.
Can some body give me a clue how to inject properties value inside a method.
Thanks in advance
Try
#Value("#{propertyConfigurer['tutor.mail.common.note']}")
private static String NOTE;
For more info have a look at How can I inject a property value into a Spring Bean which was configured using annotations?

Why is this spring bean not initialised? It is always null.

I have a message factory bean configured as shown below:
<?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:ws="http://www.springframework.org/schema/web-services"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/web-services
http://www.springframework.org/schema/web-services/web-services-2.0.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-3.0.xsd">
<bean id="soapMessageFactory" class="javax.xml.soap.MessageFactory" factory-method="newInstance" />
<bean id="saajMessageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory">
<constructor-arg ref="soapMessageFactory" />
</bean>
<bean id="myService" class="com.mypackage.TestEndPoint">
<property name="saajMessageFactory" ref="saajMessageFactory" />
</bean>
</beans>
The TestEndpoint class looks like this
#Endpoint
public class TestEndPoint {
ObjectFactory objectFactory = new ObjectFactory();
SaajSoapMessageFactory saajMessageFactory;
#PayloadRoot(namespace="http://ws.mypackage.com", localPart="downloadSaajMessageRequest")
#ResponsePayload
public JAXBElement<DownloadResponseSaajType> invoke(#RequestPayload DownloadSaajMessageRequest req, MessageContext context ) throws Exception {
DownloadResponseSaajType response = new DownloadResponseSaajType();
//DownloadResponseSaajType.PayLoad payload = new DownloadResponseSaajType.PayLoad();
DataHandler handler = new javax.activation.DataHandler(new FileDataSource("c:\\temp\\maven-feather.png"));
SaajSoapMessage message = saajMessageFactory.createWebServiceMessage();
message.addAttachment("picture", handler);
message.addAttachment("picture", handler);
//payload.setMessagePayLoad(handler);
//response.setPayLoad(payload);
response.setRequestName("NAMEOF");
context.setResponse(message);
return objectFactory.createDownloadSaajMessageResponse(response);
}
public void setSaajMessageFactory(SaajSoapMessageFactory saajMessageFactory){
this.saajMessageFactory = saajMessageFactory;
}
public SaajSoapMessageFactory getSaajMessageFactory(){
return saajMessageFactory;
}
}
I am having a few problems trying to get the endpoint to work and when i tried to debug the code i found that saajMessageFactory is never initialised and it is always null. Have i done something wrong with the configuration?
You have to add PayloadRootAnnotationMethodEndpointMapping bean to your configuration xml.
<bean class="org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping"/>

Spring MVC 3.1 RedirectAttributes is not working

I'm trying to implement RedirectAttributes feature in Spring MVC 3.1-Release
I'm sending simple form to Post URL and would like to see the the value I'm sending in redirect:
my Controller looks like this:
#Controller
public class DefaultController {
#RequestMapping(value="/index.html", method=RequestMethod.GET)
public ModelAndView indexView(){
ModelAndView mv = new ModelAndView("index");
return mv;
}
#RequestMapping(value="/greetings.action", method=RequestMethod.POST)
public ModelAndView startTask(#RequestParam("firstName") String firstName,RedirectAttributes redirectAttributes){
redirectAttributes.addFlashAttribute("redirectAttributes.firstName", firstName);
ModelAndView mv = new ModelAndView(new RedirectView("success.html"));
return mv;
}
#RequestMapping(value="/success.html", method=RequestMethod.GET)
public ModelAndView successView(){
ModelAndView mv = new ModelAndView("success");
return mv;
}
}
Now my Servlet XML looks like this:
<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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="com.vanilla.flashscope.controllers" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
My problem is that in success.html view redirectAttributes is empty.
<body>
<h5>${redirectAttributes.firstName} </h5>
</body>
Prints nothing.
It does not work because You are using ModelAndView as a return value.
See JIRA Issue: https://jira.springsource.org/browse/SPR-8968
It looks like you need to remove "redirectAttributes." from the key name"
Instead of:
redirectAttributes.addFlashAttribute("redirectAttributes.firstName", firstName);
Do this:
redirectAttributes.addFlashAttribute("firstName", firstName);

Categories