delete all records in mongoDB Spring application using CURL - java

I'm Working with one of Spring's tutorials on integrating Spring with Mongo DB.
https://spring.io/guides/gs/accessing-mongodb-data-rest/
I simply want to be able to delete multiple records using CURL.
something like
curl -X DELETE http://localhost:8080/people/
The tutorial shows how to delete a specific record but not multiple records. Fairly new with working with CURL as well..Pretty sure I'm missing something simple, thanks.
FYI the method to delete a single record would be
curl -X DELETE http://localhost:8080/people/53149b8e3004990b1af9f229

I think, you should run this
mongo <dbname> --eval "db.people.drop()"

When you run the example project you linked, Spring Boot automatically wires a RepositoryEntityController, that exposes basically two URIs:
http://localhost:8080/people/
and
http://localhost:8080/people/{id}
where {id} is a specific person's id.
It also provides some methods and binds them with one of the URIs above. For example, there is the getCollectionResource method, that "listens to" http://localhost:8080/people/, so you can run
curl http://localhost:8080/people/
and get a list of the people saved in your database.
The method deleteItemResource on the other hand, "listens to" http://localhost:8080/people/{id}, so the specific controller does not provide the functionality of simultaneously deleting all person entities.
But you can always write your own controller and provide your custom functionality. The trivial code below will do the work (but will not include all the other methods of course):
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/people")
public class PersonController {
#Autowired
PersonRepository people;
#RequestMapping(method=RequestMethod.DELETE)
public void deleteAll() {
people.deleteAll();
}
}

Related

Grails 2.4.5 Rest API GET Request: Can't get Response Body from CUrl and from React UI, but can get it from Postman and Browser

Grails 2.4.5 REST Controller returning List of non Domain object DTO
What's the best way to turn a method/action into a REST Resource accessible through a GET request, without returning a domain class/entity, but with a non-domain/entity DTO class?
With SpringBoot, it will look like this:
#RestController
class EmployeeController { ...}
/**
**I am not sure that even in Spring/SpringBoot you can return a list of non entity class DTO.
** Can you return a random non entity
**/
#GetMapping("/employees")
List<EmployeeDTO> all() {
return repository.findAll();
}
For my Grails project, I am trying to return a list of DTO object having data from different domain/entities. Since the class is not a Grails domain class, how do you do that, since it doesn't follow the Grails convention?
I have the code as below:
class ClassNameController extends RestfulController{
/**
** Grails usually wants you to use call the parent constructor and and put a domain class as
** a parameter like super (DomainClass).
** In my case, since I have a non-conventional Controller which combines different data
** sources/domains/entities, how do I implement my method/action to turn it into a Grails REST
** Resource?
** Is there an annotation like #RestController, #ResponseBody and #GetMapping in Grails or can they be used in Grails too, since Grails 2.4.5 is built on top of Spring?
**/
/**
** I used just one of the multiple domain/entity classes as a parameter to the parent constructor,
** in order to follow that convention like this below.
**/
ClassNameController(){
super(OneDomainClassOutOfTheManyDomainClassesInsideDTOClass)
}
List<ClassDTO> getAllDTOs(){
//allClassDTOs() is a private method inside same controller returning a list of all classDTOs
List<ClassDTO> classDTOsList = allClassDTOs()
respond classDTOsList, status: 200
}
With that code, I can see the data displayed in Postman as well as inside the browser. However, I am not able to see the data when testing with CUrl, somehow looking at the log, Grails considers the request as successful and redirect to the home page. I am not sure why that's the case. I even removed any security to see if it was due to the Oauth Access token, but I can see that it's not the case, as even with #Secured(['IS_AUTHENTICATED_FULLY']), I can see in the logs of Spring Security that the user has been authenticated successfully and the authorization access has been granted successfully.
Pretty much, I am looking for a sample example of a simple Grails REST API that doesn't use the Grails convention and returns a non domain object.

How to access HTML files **through a controller** in Spring boot without a template engine

So I have been trying hard to get a simple app to run with populating an HTML file through a controller without using a template engine.
I thought I would take some time to post about my findings related to the subject above. See answer below
Soo the question here is How to access HTML files through a controller in Spring boot without a template engine?
This is a very simplistic answer to a simple issue, this is not meant to scale and does not take into account the entirety of your project
Please keep in mind this is not the norm in a business environment but it was really bothering me how I cannot get a simple HTML to populate from a controller without using a template engine. I got it to work with thymeleaf dependency but I wanted to just get it to work as bare bones as possible. I read a lot of posts with ViewResolver Config classes or things a like but nothing worked. It would conflict with the internal resolvers of Spring boot.
Simple answer is once spring boot is initialized...all your static files must be in resources/static/
Templates folder is specific to use for Thymeleaf, based on my findings and it wont work if you just put it in the resource folders.
With your files in resources/static/ you can access it by going to localhost:8080/yourfilename.html
But if you want to access it through a controller you create a controller with the following:
#Controller
public class IndexController {
#RequestMapping("/")
public String getIndex(){
return " index.html";
}
}
If you want to remove the .html in your return value then you must add the following to your application.properties file
spring.mvc.view.suffix=.html
Then you can use the following
#Controller
public class IndexController {
#RequestMapping("/")
public String getIndex(){
return " index";
}
}
Once again this is a simple research I did on my own just to get it to work.

How to identify whether web service is REST or SOAP?

I am learning spring MVC and have wrote following code. I read some articles about SOAP and REST but in the beginner level controller code I have written I am not able to distinguish whether SOAP or REST is used. My controller code is as follows:
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.model.Customer;
#Controller
public class SelectController {
#RequestMapping("/")
public String display(){
System.out.println("Inside controller");
return "demo";
}
#RequestMapping("/index")
public String indexpage(HttpServletRequest req, Model m){
String name = req.getParameter("name");
String pass = req.getParameter("pass");
String random = req.getParameter("abc");
System.out.println("Index page"+name+pass+random);
Customer cust = new Customer();
cust.setUsername(name);
cust.setPassword(pass);
System.out.println("Index page"+name+pass);
m.addAttribute("customer", cust);
return "hello";
}
The Controller that you have written is
neither REST nor SOAP.
Its a MVC Controller.
In your case, your returning "hello" string at the end of controller method, which in-turn gets translated/mapped to a page(hello.jsp or hello.html based on the configuration) and returns the same. So, at the end, what you get is Page rendered in a beautiful way with all the necessary Stylings and scripts applied.
In contrast, REST and SOAP doesn't work in that way. Its main purpose is for transferring the data alone(Yet you can send HTML page also)
Writing a REST Service is almost similar to what you have currently and is fairly easy. If you use Springboot then all you have to do is just replace the #Controller annotation with #RestController and return Customer object directly. In REST Controller you wont have HttpServletRequest & Model arguments.
But writing a SOAP service is another topic which may seem entirely different.
There are tons of examples and tutorials scattered around the web, which you can find easily on these topics.
References :
Controller vs RestController in Spring
Difference between Controller & RestController in Spring
SOAP vs REST
Hope this gives some high level idea of what those three are.

Spring cache/fallback framework

My use case is that I want to cache certain request:response in my service caller classes:
public class Abc{
public Response serviceCall(Request r){}
}
public class Memcached{
public Response get(Request r){}
public void put(Request r, Response rs){}
}
I want to use memcached for caching . The request would be the key and value would be the response. Whenever serviceCall() is called I want to check if request is already present in cache if so then return response from the cache.
If not then actually execute serviceCall() method and put request:response key:value in memcached
Is there any way in spring to achieve the same.
I did look into #Cacheable here http://www.baeldung.com/spring-cache-tutorial
But I am unable to understand how I make spring use my "Memcached" class, more specifically where do I wire my "Memcached" class so that it is available to class "Abc" in above example
Could you please help . I am working in spring boot completely annotation based and looking for annotation based solution
Spring caching doesn't support Memcached by out-of-the-box (Supported Cache Providers).
If you want to use Memcached in your project please check out Memcached Spring Boot caching library.
There is also an example Java project of how to use Memcached with Spring.
You don't need the memcached class. Just put the #Cacheable annotation on Abc.serviceCall as per the baeldung tutorial.

Spring, #WebService / #WebMethod, (using Jax-WS), receiving a serialized object?

I've been gradually piecing together how I can receive a serialized object within Spring and have gotten a web service working, by following a tutorial, that uses Jax-WS. I have verified that I can access this basic service through a browser by pulling up the XML page using a url like http://localhost:8080/WebServicesExample/hello?wsdl
The code I currently have is like below, however I want to make a service so that a serialized object can be passed in, for example a HashMap and then have spring de-serialize it, etc. I have been doing a lot of reading on this but am still a bit lost, I would appreciate if anyone can offer advice how to get from where I am at currently to what I am trying to do. Thanks
import javax.jws.WebMethod;
import javax.jws.WebService;
import com.mkyong.bo.HelloWorldBo;
#WebService
public class HelloWorldWS{
//DI via Spring
HelloWorldBo helloWorldBo;
#WebMethod(exclude=true)
public void setHelloWorldBo(HelloWorldBo helloWorldBo) {
this.helloWorldBo = helloWorldBo;
}
#WebMethod(operationName="getHelloWorld")
public String getHelloWorld() {
return helloWorldBo.getHelloWorld();
}
}
I am not completely sure which WS stack you have used for exposing this service, assuming that you just want to create a JAX-WS based sample, let me point you to a working sample that I had created earlier available at : git://github.com/bijukunjummen/memberservice-codefirst.git .
This sample uses Apache CXF as the JAX-WS implementation, and uses JAXB2 for binding (converting the incoming xml to Java objects and back)
In your example, Apache CXF would allow you to expose a WS interface using an entry into spring configuration files of the type:
<jaxws:endpoint address="/helloworldservice" id="helloworld" implementor="#helloworldBean" >
</jaxws:endpoint>

Categories