RoutePrefix in web api dont start controller - javascript

I need to start Index from Controller before opening page and that was working but when i added RoutePrefix controller didn't want to start. What should be done so i can start controller even with RoutePrefix.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { controller = "main", id = RouteParameter.Optional }
);
}
}
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Main", action = "Index", id = UrlParameter.Optional }
);
}
}
[RoutePrefix("api/main")]
public class MainController : ApiController
{
private static List<Korisnik> adminlist = new List<Korisnik>();
private static List<Vozac> vozaclist = new List<Vozac>();
private static List<Korisnik> korisniklist = new List<Korisnik>();
[HttpGet, Route("")]
public RedirectResult Index()
{
ReadFromXML(Enums.Uloga.Dispecer);
var requestUri = Request.RequestUri;
return Redirect(requestUri.AbsoluteUri + "Content/index.html");
}

Related

Getting null values in postman while fetching data from database using springboot although data is present in database, through userId/categoryId

I am trying to create a blog apis but Getting null values in postman while fetching data from database although data is present in database using springboot, when i am trying to get data by userId or categoryId. it's giving me null value as shown.
{ "postTitle": null, "postContent": null, "postImageName": null,
"postAddedDate": null, "category": null, "user": null }
// Controller Class
#RestController
#RequestMapping("/api/")
public class PostController {
#Autowired
private PostService postService;
// create
#PostMapping("/user/{userId}/category/{categoryId}/posts")
public ResponseEntity<PostDto> createPost(#RequestBody PostDto postDto, #PathVariable Integer userId,
#PathVariable Integer categoryId) {
PostDto createdPost = this.postService.createPost(postDto, userId, categoryId);
return new ResponseEntity<PostDto>(createdPost, HttpStatus.CREATED);
}
// get post by user
#GetMapping("/user/{userId}/posts")
public ResponseEntity<List<PostDto>> getPostByUser(#PathVariable Integer userId) {
List<PostDto> posts = this.postService.getPostByUser(userId);
return new ResponseEntity<List<PostDto>>(posts, HttpStatus.OK);
}
// get post by category
#GetMapping("/category/{categoryId}/posts")
public ResponseEntity<Set<PostDto>> getPostByCategory(#PathVariable Integer categoryId) {
Set<PostDto> posts = this.postService.getPostByCategory(categoryId);
return new ResponseEntity<Set<PostDto>>(posts, HttpStatus.OK);
}
}
//Post Entity Class
#Entity
#Table(name = "post")
#Getter
#Setter
#NoArgsConstructor
public class Post {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer postId;
private String postTitle;
#Column(length = 10000)
private String postContent;
private String postImageName;
private Date postAddedDtae;
#ManyToOne
#JoinColumn(name = "category_id")
private Category category;
#ManyToOne
private User user;
}
//Post Dto Class
#Getter
#Setter
#NoArgsConstructor
public class PostDto {
private String postTitle;
private String postContent;
private String postImageName;
private Date postAddedDate;
private CategoryDto category;
private UserDto user;
}
//Post Repo class
public interface PostRepo extends JpaRepository<Post, Integer> {
List<Post> findByUser(User user);
Set<Post> findByCategory(Category category);
}
//Post Service Class
public interface PostService {
// create
PostDto createPost(PostDto postDto, Integer userId, Integer categoryId);
// update
Post updatePost(PostDto postDto, Integer posId);
// getAll
List<PostDto> getAllPost();
// getSinglepost
Post getPostByid(Integer PostId);
// Delete
void deletePost(Integer postId);
// getPOstByCategory
Set<PostDto> getPostByCategory(Integer categoryId);
// getAllPostByUser
List<PostDto> getPostByUser(Integer userId);
// Search Post
List<PostDto> searchPosts(String keyword);
}
//Post ServiceImplmentation class
#Service
public class PostServiceImpl implements PostService {
#Autowired
private PostRepo postRepo;
#Autowired
private ModelMapper modelMapper;
#Autowired
private UserRepo userRepo;
#Autowired
private CategoryRepo categoryRepo;
#Override
public PostDto createPost(PostDto postDto, Integer userId, Integer categoryId) {
User user = this.userRepo.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("User", "User Id", userId));
Category category = this.categoryRepo.findById(categoryId)
.orElseThrow(() -> new ResourceNotFoundException("Category", "Category Id", categoryId));
Post post = this.modelMapper.map(postDto, Post.class);
post.setPostImageName("Default.png");
post.setPostAddedDtae(new Date());
post.setUser(user);
post.setCategory(category);
Post newPost = this.postRepo.save(post);
return this.modelMapper.map(newPost, PostDto.class);
}
#Override
public Post updatePost(PostDto postDto, Integer posId) {
// TODO Auto-generated method stub
return null;
}
#Override
public List<PostDto> getAllPost() {
// TODO Auto-generated method stub
return null;
}
#Override
public Post getPostByid(Integer PostId) {
// TODO Auto-generated method stub
return null;
}
#Override
public void deletePost(Integer postId) {
// TODO Auto-generated method stub
}
#Override
public Set<PostDto> getPostByCategory(Integer categoryId) {
Category cat = this.categoryRepo.findById(categoryId)
.orElseThrow(() -> new ResourceNotFoundException("Category", "Category Id", categoryId));
Set<Post> posts = this.postRepo.findByCategory(cat);
Set<PostDto> postDtos = posts.stream().map((post) -> this.modelMapper.map(posts, PostDto.class))
.collect(Collectors.toSet());
return postDtos;
}
#Override
public List<PostDto> getPostByUser(Integer userId) {
User user = this.userRepo.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("User", "User Id", userId));
List<Post> posts = this.postRepo.findByUser(user);
List<PostDto> postDtos = posts.stream().map((post) -> this.modelMapper.map(posts, PostDto.class))
.collect(Collectors.toList());
return postDtos;
}
#Override
public List<PostDto> searchPosts(String keyword) {
// TODO Auto-generated method stub
return null;
}
}
Please check and let me know where i am going wrong...

Angular Call to MVC Controller Function

I'm fairly new to Angular and I am having some trouble finding the answer to my problem. I'm using Angular 11 with ASP.NET MVC in visual studio, and I am trying to invoke a MVC controller once a button is clicked in my app.component.html. I have looked all over the place, but all the answers are either for AngularJS or ASP.NET Core which doesn't really help me at all. Any help would be greatly appreciated.
Thanks!
app.component.html
<div style="padding-left: 140px">
<button (click)="onImportClick()" class="dv-button" style="width:
100px; padding: 4px 6px">
Import
</button>
</div>
app.component.ts
onImportClick() {
this.importErrors = [];
this.appService.callImport(4).subscribe()
this.clearFile();
//window.location.reload();
}
}
app.service.ts
export class AppService {
private baseUrl = "http://localhost:4200/";
private importUrl = this.baseUrl + 'Import/GetTest';
private test = ["test"];
myBooks: string[];
constructor(private http: HttpClient) { }
callImport(id: any) {
let body = JSON.stringify(id);
return this.http.get('Import/GetTest').pipe(map(
data => {
this.myBooks = [body];
}
)
);
}
ImportController.cs
namespace AI.Controllers.AI_API
{
public class ImportController: IController
{
public void Execute(RequestContext requestContext)
{
throw new NotImplementedException();
}
[Route("/Import/GetTest")]
public int GetTest(int id)
{
var result = id;
return result;
}
}
}
RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}",
defaults: new { controller = "Home", action = "Index"}
);
}
}

test class is unable to read consul config

I have test code in which I want to read configurations from consul.The application.properties (src/main/resources) enables the consul config. And I have one POJO class name DBConfig (in src/main/java) which gets the configuration from consul. I have autowired the DBConfig in test class and when I'm running the unit test it is giving me nullpointerexception as it is not getting the values from consul.
How to handle the situation. Please help.
#Configuration
#ConfigurationProperties(prefix="db")
#RefreshScope
public class DBConfig {
private String jdbcURL;
private String username;
private String password;
private String driverClass;
...getter setters.
}
Test Class---
#RunWith(MockitoJUnitRunner.class)
#Transactional(propagation=Propagation.REQUIRED,readOnly=false,rollbackFor=Exception.class)
#SpringBootTest(classes={DBConfig.class})
public class TestUserDao extends DBTestCase {
#Autowired
private DBConfig dbConfig;
protected final Resource res = new ClassPathResource("actualDataSet.xml");
#Bean
#Profile("test")
#RefreshScope
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(dbConfig.getDriverClass());
dataSource.setUrl(dbConfig.getJdbcURL());
dataSource.setUsername(dbConfig.getUsername());
dataSource.setPassword(dbConfig.getPassword());
return dataSource;
}
#Bean
#Autowired
public NamedParameterJdbcTemplate jdbcTemplate(DataSource dataSource) {
return new NamedParameterJdbcTemplate(dataSource);
}
#Bean
#Autowired
public UserDAO userDAO(NamedParameterJdbcTemplate jdbcTemplate) {
return new UserDAO(jdbcTemplate);
}
#Override
protected IDataSet getDataSet() throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
String file = classLoader.getResource("actualDataSet.xml").getFile();
return new FlatXmlDataSetBuilder().build(new FileInputStream(file));
}
protected DatabaseOperation getSetUpOperation() throws Exception {
return DatabaseOperation.REFRESH;
}
#Test
public void insertTodo() throws Exception {
}
protected DatabaseOperation getTearDownOperation() throws Exception {
return DatabaseOperation.DELETE;
}
It may be caused by usage of MockitoJUnitRunner class, which will not load ApplicationContext at startup, which means, your beans won't be accessible.
Once you will use SpringRunner class in #RunWith() annotation, Spring should be able to inject DBConfig bean.

cors in spring boot app

I have a table called student with column name, password, domain.
I have a method in my controller that provides token to student for getting some resources.
#CrossOrigin(origins = "*")
#RequestMapping(value = "/getToken")
public String provideToken() {
return "tokenvalue"
}
In the database, there are multiple students and multiple student have different domain that calls the above method. E.g.
something.com/provideToken?username="user"&password="pass"
In different domain there is a page that calls the above url.
Now, How do i make sure that only those domain that are in the database can access above provideToken function.
public static void main(String[] args) throws InterruptedException {
SpringApplication.run(Application.class, args);
}
#Bean
public WebMvcConfigurer corsConfigurer() {
List<User> allUsers = userDao.findAll();
List<String> originList = new ArrayList<>();
for(User user: allUsers) {
originList.add(user.getDomainName());
}
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
String[] origins = new String[originList.size()];
origins = originList.toArray(origins);
registry.addMapping("/getToken").allowedOrigins(origins);
}
};
}
You can use a WebMvcConfigurer for programmatic configuration of origins per mapping:
#SpringBootApplication
#RestController
public class MySpringBootApplication {
#Autowired
private MyDatabase myDatabase;
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
String[] origins = myDatabase.getAllowedOriginsForGetToken(); // example
registry.addMapping("/getToken").allowedOrigins(origins);
}
};
}
...
As you can see, it allows you to go to the database (or any other source) for getting the origins information.

What is the service name for the EntityManager in Breeze?

I just don't understand what I have to set as the service name for the EntityManager.
I hava two controllers: an ApiController and a 'normal' controller:
API Controller:
[BreezeController]
public class TournamentApiController : ApiController
{
private EFContextProvider<TournamentContext> _contextProvider;
public TournamentApiController()
{
_contextProvider = new EFContextProvider<TournamentContext>();
}
[HttpGet]
public string Metadata()
{
return _contextProvider.Metadata();
}
[HttpGet]
public IQueryable<Tournament> Tournaments()
{
return _contextProvider.Context.Tournaments;
}
[HttpGet]
public IQueryable<Team> Teams()
{
return _contextProvider.Context.Teams;
}
}
'Normal' controller:
public class TournamentController : Controller
{
public ActionResult Index()
{
return PartialView();
}
public ActionResult Details()
{
return PartialView();
}
}
And in my DataSrvice.js file:
app.dataservice = (function (breeze) {
breeze.config.initializeAdapterInstance("modelLibrary", "backingStore", true);
var serviceName = '/TournamentApi'; // What exactly do I need to set here?
// *** Cross origin service example ***
//var serviceName = 'http://todo.breezejs.com/breeze/todos'; // controller in different origin
var manager = new breeze.EntityManager(serviceName);
// manager.enableSaveQueuing(true);
var dataservice = {
getAllTournaments: getAllTournaments,
};
return dataservice;
/*** implementation details ***/
function getAllTournaments() {
var query = breeze.EntityQuery
.from("Tournament");
return manager.executeQuery(query);
}
})(breeze);
Can someone explain what is meant by a service name and thus, what I should use as the service name?
The serviceName identifies the service end-point, the route to the Web API controller. This will be the "root" of the URL you use to communicate with the server. So if the actual endpoints to query 'teams' and 'tournaments' are
http://foo/bar/tournamentApp/teams ...
http://foo/bar/tournamentApp/tournaments ...
then your service name will be
"foo/bar/tournamentApp"

Categories

Resources