I am trying to start with a simple web service following the example : https://spring.io/guides/gs/rest-service/
I am unable to get any response when I hit the service URL. The way I am trying to run this is by running the project on Apache web server from Eclipse.
This is my controller:
package com.nscm.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.nscm.model.User;
#RestController
public class NSCMController {
#RequestMapping("/getuser")
public User getUser()
{
System.out.println("NSCMController.getUser()");
return new User();
}
}
This is my service class:
package com.nscm.service;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;
#ComponentScan("com")
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
System.out.println("Application.main()");
SpringApplication.run(Application.class, args);
}
}
Even though as the example mentions the web.xml and the spring.xml is not required, even after placing these, my code does not work. None of the SOPs are called when I hit the URL. Please help me if I am missing anything here.
Related
I want to write the Unit test using PowerMockito/Mockito for my static method/void method.
But When I try to run , I got the following error:
/Users/<username>/Library/Java/JavaVirtualMachines/corretto-
---- IntelliJ IDEA coverage runner ----
sampling ...
include patterns:
exclude patterns:
ScriptEngineManager providers.next(): javax.script.ScriptEngineFactory: Provider jdk.nashorn.api.scripting.NashornScriptEngineFactory not a subtype
ScriptEngineManager providers.next(): javax.script.ScriptEngineFactory: Provider jdk.nashorn.api.scripting.NashornScriptEngineFactory not a subtype
java.lang.NoSuchMethodError: org.mockito.MockingDetails.getMockHandler()Lorg/mockito/invocation/MockHandler;
at org.powermock.api.mockito.invocation.MockHandlerAdaptor.getMockHandler(MockHandlerAdaptor.java:56)
at org.powermock.api.mockito.invocation.MockHandlerAdaptor.createInvocation(MockHandlerAdaptor.java:81)
at org.powermock.api.mockito.invocation.MockHandlerAdaptor.performIntercept(MockHandlerAdaptor.java:61)
at org.powermock.api.mockito.invocation.MockitoMethodInvocationControl.invoke(MockitoMethodInvocationControl.java:93)
at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:186)
at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:168)
at org.powermock.core.MockGateway.methodCall(MockGateway.java:138)
I am new to use powerMockito/Mockito, Can Anyone help to figure out the exact issue.
This is my CreateTaskBuilder Class method that I want to test:
Here JgitAccessor.clone() is a static void methid that I used donothing() for it.
public void Repository() throws DependencyFailureException, IOException, GitAPIException {
try {
ServiceAccessor.loadTmpSshTicket();
if (!Files.exists(Paths.get(LambdaEnv.GIT_SSH_SCRIPT.getValue()))) { // getValue will throw exception on null
throw new IllegalStateException(String.format("Environment variable GIT_SSH points to file %s but it doesn't exist.",
LambdaEnv.GIT_SSH_SCRIPT.getValue()));
}
JgitAccessor.clone(REPO_URI, CLONED_REPO_PATH);
} catch (IOException | DependencyFailureException e) {
log.info("Exception occurred while performing Service client integration. exception: [{}]", e.getMessage());
e.printStackTrace();
}
}
And this is the unit test class :
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.mockito.Mockito.*;
#RunWith(PowerMockRunner.class)
#PowerMockIgnore({"javax.management.*"})
#PrepareForTest({CreateTaskBuilder.class, LambdaEnv.class, ServiceAccessor.class, JgitAccessor.class})
public class CreateTaskBuilderTest extends TestUtils {
#Mock
private ServiceAccessor serviceAccessor;
#Mock
private JgitAccessor jgitAccessor;
#InjectMocks
CreateTaskBuilder builder;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
#Test
public void loadServiceTicket_happyCase() throws Exception {
doNothing().when(serviceAccessor).loadTmpSshTicket();
PowerMockito.mockStatic(System.class);
Mockito.when(System.getenv("GIT_SSH")).thenReturn("/tmp/ssh.sh");
PowerMockito.mockStatic(Files.class);
Mockito.when(Files.exists(Paths.get("/tmp/ssh.sh"))).thenReturn(true);
PowerMockito.mockStatic(JgitAccessor.class);
PowerMockito.doNothing().when(JgitAccessor.class, "clone", Mockito.anyString(), Mockito.anyString());
builder.cloneRepository();
}
I am using Mockito = 2.28.x; PowerMockMockito = 2.x;
It looks like you have the wrong versions of libraries on your classpath.
The version of PowerMock you are using requires a Mockito with an org.mockito.MockingDetails.getMockHandler() which is not available in Mocktio 2.8.x. You can find it in a later version in 2.23.x.
Looking at minimum version dependencies for powermock-api-mockito2 version 2.0.0 you should be using mockito version 2.23.0 or later.
So looks like you need to update Mockito to a later version compatible with your PowerMock version, 2.23.x or later instead of 2.8.x.
Everytime i try to show the results from the page, it downloads the results in json format instead of showing them on page.
It starts to download when i enter the url where the objects/information is stored, instead of showing the page http://localhost:8082/spring-rest-demo/api/students
If i run the server and paste this info in postman og google chrome, it does show the correct information without downloading it as a json file.
this is how it should be
Thank you
Edit:
package com.luv2code.springdemo.rest;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.luv2code.springdemo.entity.Student;
#RestController
#RequestMapping("/api")
public class StudentRestController {
private List<Student> theStudents;
// define #PostConstruct to load the student data only once!
#PostConstruct
public void loadData() {
theStudents = new ArrayList<>();
theStudents.add(new Student("Poornima", "Patel"));
theStudents.add(new Student("Mario", "Rossi"));
theStudents.add(new Student("Mary", "Smith"));
}
// define endpoint for "/Student"-- return list of students
#GetMapping("/students")
public List<Student> getStudents() {
return theStudents;
}
// define endpoint for "/Student({studentid}"-- return list of students at index
#GetMapping("/students/{studentId}")
public Student getStudent(#PathVariable int studentId) {
// just index into the list .... keep it simple for now
return theStudents.get(studentId);
}
}
Try to add produces application/json in #GetMapping annotation.
This is a bug in recent versions of Eclipse. Hopefully the Eclipse team will fix it soon
This question already has answers here:
Serving static web resources in Spring Boot & Spring Security application
(9 answers)
Closed 4 years ago.
As stated in the title, when a user is greeted with the welcome page of my spring webapp the embedded html images wont load, just showing the broken image icon.
When the user logs in the images are all viewable.
No errors are coming up and I have a feeling it is related to a Spring Security feature, is there any solutions/work arounds for this?
My HTML code:
<a> <img src="src/main/resources/static/images/logo.jpg"> </img></a>
My Controller:
#RequestMapping(value={"/","home"})
public String home(){
return "home";
}
My WebSecurity:
package com.FYP.Club.Security;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import com.FYP.Club.repository.UserLoginRepository;
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
UserLoginRepository userLoginRepository;
//http.authorizeRequests().antMatchers("/", "/home", "/registeruser").permitAll().antMatchers("/admin").hasRole("ADMIN")
#Autowired
DataSource dataSource;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "/home", "/registeruser").permitAll().antMatchers("/admin").hasRole("ADMIN")
.anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout()
.permitAll();
http.exceptionHandling().accessDeniedPage("/403");
http.csrf().disable();
//disable csrf to allow communication (we also dont need for this fyp as its not live)
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select user_name,password,user_status from user_login where user_name=?")
.authoritiesByUsernameQuery("select user_name, password from user_login where user_name=?");
}
}
Let me know if you need more code!
You should configure them to be ignored by Spring Security.
For example by adding such method to your WebSecurityConfig:
#Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/fonts/**", "/images/**", "/css/**");
}
if you request the images with such link:
<a> <img src="/images/logo.jpg"> </img></a>
I am trying to utilise RTMPGW as part of my app, which usually works great in Linux. I am trying to use the Vitamio bundle to play back the stream. Here is the main code, taken from the Vitamio Demo:
package io.vov.vitamio.demo;
import io.vov.vitamio.MediaPlayer;
import io.vov.vitamio.widget.MediaController;
import io.vov.vitamio.widget.VideoView;
import android.app.Activity;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
public class VideoViewDemo extends Activity {
private VideoView mVideoView;
/* (non-Javadoc)
* #see android.app.Activity#onCreate(android.os.Bundle)
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
if (!io.vov.vitamio.LibsChecker.checkVitamioLibs(this))
return;
setContentView(R.layout.videoview);
mVideoView = (VideoView) findViewById(R.id.surface_view);
mVideoView.setVideoURI(Uri.parse("http://172.16.1.182:8902/?r=rtmp://live.dtv.cubecdn.net:80/kdmobil/KanalD1&W=http://www.kanald.com.tr/Content/swf/Canliplayer6.swf?config=/Content/swf/Config.xml%26debug=false&p=http://www.kanald.com.tr&c=80"));
mVideoView.setVideoQuality(MediaPlayer.VIDEOQUALITY_HIGH);
mVideoView.setMediaController(new MediaController(this));
mVideoView.requestFocus();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
if (mVideoView != null)
mVideoView.setVideoLayout(VideoView.VIDEO_LAYOUT_SCALE, 0);
super.onConfigurationChanged(newConfig);
}
}
When I run this, RTMPGW (which I am running from the terminal in Linux) displays this error:
processTCPrequest, Range request not supported
..and sits there idly, doing nothing.
However, when I use regular Android VideoView with this code (in a different project):
package com.sample.videoviewexample;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;
public class MainActivity extends Activity {
private VideoView mVideoView;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
mVideoView = (VideoView) findViewById(R.id.surface_view);
mVideoView.setVideoURI(Uri.parse("http://172.16.1.182:8902/?r=rtmp://live.dtv.cubecdn.net:80/kdmobil/KanalD1&W=http://www.kanald.com.tr/Content/swf/Canliplayer6.swf?config=/Content/swf/Config.xml%26debug=false&p=http://www.kanald.com.tr&c=80"));
mVideoView.setMediaController(new MediaController(this));
mVideoView.requestFocus();
}
}
It connects to the RTMPGW server and starts streaming like so...
Streaming on http://0.0.0.0:8902
processTCPrequest, Range request not supported
Connecting ... port: 80, app: kdmobil/KanalD1
1094.914 KB / 16.90 sec
But, of course, as Android MediaPlayer doesn't support Flash natively it won't play back the video.
Why does the VideoView connect with RTMPGW's server but Vitamio doesn't?
Thanks for your help,
Dan
In my entities I have some hibernate annotations for validation, like #NotEmpty, #Pattern.. and others
In my controller, on save action, it has an #Valid parameter.
But if any entity has any required field, and there is no annotation I will have problems.
So I would like to test each entity, to ensure they have the necessary notes.
Something like:
#Test(expect=IllegalArgumentException.class)
public void testAllNull() {
Person p = new Persson(); // Person name has an #NotEmpty
validator.validate(p);
}
But how to validate it? Who is called to check #Valid?
Thanks.
I found out how to check:
#Autowired
private LocalValidatorFactoryBean validator;
...
validator.validateProperty(object, propertyName)
Here is a Spring v4.1.x based example of a test validating presence and processing of the #Valid annotation and building of custom JSON response in case of an error.
jUnit
import com.fasterxml.jackson.core.type.TypeReference;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import javax.inject.Inject;
import java.util.List;
import static org.abtechbit.miscboard.util.JsonUtils.toJson;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {
RegistrationValidationTest.MockDependencies.class,
})
public class RegistrationValidationTest {
#Inject
MockMvc mvc;
#Test
public void validatesRegistration() throws Exception {
Registration registration = ... //build an invalid Registration object
MvcResult result = mvc.perform(post(RegistrationController.CONTEXT_REGISTER).
contentType(MediaType.APPLICATION_JSON).
content(toJson(registration))).
andExpect(status().isBadRequest()).
andExpect(content().contentType(MediaType.APPLICATION_JSON)).
andReturn();
assertThat(result.getResolvedException(), is(notNullValue()));
String content = result.getResponse().getContentAsString();
assertThat(content, is(notNullValue()));
List<Message> messages = JsonUtils.fromJson(content, new TypeReference<List<Message>>() {
});
assertThat(messages.size(), is(1));
}
public static class MockDependencies {
#Bean
public MockMvc mvc() {
return MockMvcBuilders.standaloneSetup(new RegistrationController()).build();
}
}
}
Controller
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;
#Controller
public class RegistrationController
{
public static final String CONTEXT_REGISTER = "/register";
#RequestMapping(value = CONTEXT_REGISTER, method = RequestMethod.POST)
#ResponseBody
public String register(#RequestBody #Valid Registration registration) {
//perform registration
}
#ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<List> handleValidationException(MethodArgumentNotValidException ex) {
//Build a list of custom Message{String message;} objects
List<Message> messages = ex.getBindingResult().getAllErrors().
stream().map(e->new Message(e.getDefaultMessage())).collect(Collectors.toList());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).contentType(MediaType.APPLICATION_JSON).body(messages);
}
}
Spring MVC Test Framework might be a good choice. By using this, you can be assured that validations in your tests runs codes as Spring #MVC actually works.
Actually, the #Valid annotation is detected by HandlerMethodInvoker, which processes annotations on the handler methods of Spring controllers. Internally, the actual validation logic is delegated to the Validator bean depending on your application context settings. (Hibernate Validator is widely used.)
By default configuration (e.g. <mvc:annotation-driven />), LocalValidatorFactoryBean is used internally to process #Valid annotation as #Falci noted, but it may differ time to time. Instead, Spring MVC Test Framework provides the same environment as the main application uses, hence a good choice.